Abstract Factory Or Factory Method

hatFactory The Gang of Four, in their seminal work Design Patterns: Elements of Reusable Object-Oriented Software, describe several creational design patterns. First off, you should be convinced that it is a best practice to separate the classes that actually do stuff from the classes that create the objects that do stuff. If you are, then these patterns are important. These patterns include the factory method and abstract factory patterns. It has often confused me as to when you should use either. I found a rather good overview in some computer science course notes. Let me quote the relevant section:

Sometimes it is difficult to differentiate between abstract factory and factory method. Solution?

  • In the factory method, your class looks down (inheritance) for help in creating the object of specific type.
  • In abstract factory, it looks to the left or right (association) for that help.

So use factory method if:

  1. your class depends on a subclass to decide what object to create.
  2. inheritance plays a vital role.

However, if your class depends on another class, which may be abstract and you are associated with it, then use abstract factory.

Alright, that’s kind of helpful. Here is how I think about it. You use the abstract factory when you have different families of similar things you need to create. You use the factory method when you have one family of things you need to create.

For example, you have one store that creates several different kinds of pizza (cheese, pepperoni, vegetable): use the factory method. You have two pizza store chains that each produce different kinds of pizza (cheese, pepperoni, vegetable): use the abstract factory.

 

Photo Credit: Sara Richards

Leave a comment

Name: (Required)

eMail: (Required)

Website:

Comment: