When is factory method better than simple factory and vice versa?

Posted by Bruce on Stack Overflow See other posts from Stack Overflow or by Bruce
Published on 2010-06-17T03:06:07Z Indexed on 2010/06/17 3:13 UTC
Read the original article Hit count: 268

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!

© Stack Overflow or respective owner

Related posts about design-patterns

Related posts about object-oriented-design