Search code examples
javadesign-patternsfactory-pattern

Understanding the factory method pattern


I'm reading about the Factory Method pattern.

I can understand when there is a single factory class, i.e. StoreFactory#getStore(), that returns a Store implementation based on some runtime or other state.

But, from reading (e.g. this link), there seems to be a general pattern of people creating an abstract factory class, to which other factory classes extend:

 public abstract class AbstractFactory {
     public abstract Store getStore(int store);
 }

 public class StoreFactoryA extends AbstractFactory {
     public Store getStore(int Store) {
         if(Store == 1) { return new MyStoreImplA(); }
         if(Store == 2) { return new MyStoreImplB(); }
     }
 }

 public class StoreFactoryB extends AbstractFactory {
     public Store getStore(int Store) {
         if(Store == 1) { return new MyStoreImplC(); }
         if(Store == 2) { return new MyStoreImplD(); }
     }
 }

 public class Runner {
    public static void main(String[] args) {
        AbstractFactory storeFactory = new StoreFactoryA();
        Store myStore = storeFactory.getStore(1);
    }
 }

My example is contrived, but models that of the aforementioned link.

This implementation seems kind of chicken-egg to me. Use the Factory Method pattern to eliminate the need for the client code to specify a class type, yet now the client code needs to selectively choose the correct factory to use, i.e. StoreFactoryA, StoreFactoryB?

What is the reasoning behind using the abstract class here?


Solution

  • The link you are reading unfortunately does not give a realistic example of the pattern. In fact, as per the original GoF Design Patterns, this pattern is called Abstract Factory (Factory method is a different pattern).

    Abstract Factory pattern is used when you have factories that can create a family of objects. e.g. You can have and AbstractGUIFactory which can have methods createButton(), createWindow(), createTitleBar etc. And then, you would have concrete factories like WindowsGUIFactory, MacGUIFactory, MotifGUIFactory etc, each of which will produce Button, Window, TitleBar objects in their own way.

    The factory will be set to one implementation at some point in the application (probably using configuration) and then that factory will be used wherever the objects need to be created.

    If you are learning Design Patterns, the best advice is to start with the classic GoF book.