When is factory method better than simple factory and vice versa?
- by Bruce
Hi all
Working my way through the Head First Design Patterns book.
I believe I understand the simple factory and the factory method, but I'm having trouble seeing what advantages factory method brings over simple factory.
If an object A uses a simple factory to create its B objects, then clients can create it like this:
A a = new A(new BFactory());
whereas if an object uses a factory method, a client can create it like this:
A a = new ConcreteA(); // ConcreteA contains a method for instantiating the same Bs that the BFactory above creates, with the method hardwired into the subclass of A, ConcreteA.
So in the case of the simple factory, clients compose A with a B factory, whereas with the factory method, the client chooses the appropriate subclass for the types of B it wants.
There really doesn't seem to be much to choose between them. Either you have to choose which BFactory you want to compose A with, or you have to choose the right subclass of A to give you the Bs.
Under what circumstances is one better than the other?
Thanks all!