0

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?

3
  • 2
    It's better if this is not done in this class, as this couples the factory abstraction to its derivatives. When defined in the AbstractFactory class, then it should be a static method - no reason for concrete factories to inherit this as an instance member. If you don't need this to be configurable, then there's no need for the 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. Feb 13 '20 at 18:29
  • What is the purpose of this class - why does the client do AbstractFactory.createFactory("foo") instead of doing new FooFactory()? Presumably, the string "foo" comes from a configuration file for example?
    – user253751
    Feb 17 '20 at 11:26
  • Sorry, I screwed up my question. I just updated it to prevent confusion.
    – user328592
    Feb 18 '20 at 16:42