Will the Factory pattern solve my problem?

I have a requirement to create some objects that implement this interface, where the type of the concrete implementation to be created is based on the value of Enum.

I am having problems when different specific implementations require different parameters at runtime.

This example (C #) is fine:

public enum ProductCategory
{
    Modem,
    Keyboard,
    Monitor
}

public class SerialNumberValidatorFactory()
{
    public ISerialNumberValidator CreateValidator(ProductCategory productCategory)
    {
        switch (productCategory)
        {
            case ProductCategory.Modem:
                return new ModemSerialNumberValidator();
            case ProductCategory.Keyboard:
                return new KeyboardSerialNumberValidator();
            case ProductCategory.Monitor:
                return new MonitorSerialNumberValidator();
            default:
                throw new ArgumentException("productType", string.Format("Product category not supported for serial number validation: {0}", productCategory))
        }
    }
}

However, what happens if specific implementations have different constructor arguments? I cannot pass all the values ​​to the method SerialNumberValidatorFactory.CreateValidator(), so how can I continue?

I heard that the template Abstract Factoryshould solve this issue, but I'm not sure how to implement it correctly.

+5
source share
2 answers

, CreateValidator. IValidatorSettings, IModemSerialNumberValidatorSettings .., CreateValidator ProductType IValidatorSettings.

IXXXValidatorSettings .

IValidatorSettings factory.

, abstract factory - factory, factory - , .

+2

, Factory, Abstract Factory

factory Factory :

, : ( , )

public class SerialNumberValidatorFactory
{
    public static SerialNumberValidatorFactory newInstance(
           ProductCategory productCategory)
    {
        switch (productCategory)
        {
            case ProductCategory.Modem:
                return new ModemValidatorFactory();
            ....
        }
    }

    public abstract ISerialNumberValidator createValidator();
}

public class ModemValidatorFactory extends SerialNumberValidatorFactory
{
   public ISerialNumberValidator createValidator() 
   {
      return new ModemSerialNumberValidator("model", "number");
   }
}

ISerialNumberValidator = SerialNumberValidatorFactory.newInstance(productCategory).createValidator()
+2

All Articles