I have a requirement to create some objects that implement a given interface, where the type of concrete implementation being created is based on an Enum value.
I run into trouble when the different concrete 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 the concrete implementations have different constructor arguments? I can't pass in all the values to the SerialNumberValidatorFactory.CreateValidator()
method, so how do I proceed?
I've heard the Abstract Factory
pattern is supposed to solve this, but I'm not sure how to implement it properly.