So to create a concrete factory that extends from an abstract factory class, I usually create a 'producer' class to determine what abstract factory to use.
For example:
public abstract class AbstractFactoryProducer
{
public AbstractFactory createFactory(String foo)
{
if(foo.equals("foo"))
{
return new FooFactory();
}
else if (foo.equals("bar"))
{
return new BarFactory();
}
... n if elses where n is number of factories
}
Is there a way around using a ton of if/else statements or switch statements?
createFactory
method, just select a concrete factory and pass it as a dependency to a client. But, if dynamically selecting a factory, these if/else chains are OK, as they are confined to one place; once a factory is selected, polymorphism takes over. – Filip Milovanović Feb 13 '20 at 18:29AbstractFactory.createFactory("foo")
instead of doingnew FooFactory()
? Presumably, the string "foo" comes from a configuration file for example? – user253751 Feb 17 '20 at 11:26