Friday, September 02, 2005

Factory Method or Abstract Factory

Since I provided the code examples in C# for the Head First Design Patterns book, I recently got an e-mail from a reader, James Micheals, of the Head First Design Patterns book that sent me this question.
I'm trying to understand the difference between simple factory and factory method. They are the same thing! It's just one is composed while the other is inherited. I could even argue that since we prefer composition over inheritance, simple factory is better than factory method. I don't understand why factory method is better, and I've been tearing my hair out for hours to figure out why.
While I myself am a mere student of patterns here was my reply and thoughts on his question:

You have asked a good question.

The factory method is good to implement alone if you have variations of a particular object that you need to create.

The Head First book uses a pizza store as the example here. The pizza store has a limited variation of pizzas it sells. Therefore, an abstract class is implemented (extended in java) in your subclasses and you are good to go for specific pizza object creation.

The abstract factory is utilized for creating a "family of objects" and therefore often utilizes factory methods within it.

In short, which pattern is used is dependent upon your need. If a simple set of related objects is what you want, then the factory method is your pattern. If you need a more varied set of objects created, the abstract factory pattern provides this via the ability to use a set of interfaces for each desired set of objects.

You stated that composition is favored over inheritance. That is correct, but which pattern is used is dependent upon your need.

Hope this helps,


No comments: