Design Patterns: Abstract Factory vs Factory Method

user295190 picture user295190 · Nov 17, 2010 · Viewed 63.5k times · Source

Note: Questions are at the end of the post.

I have read the other stackoverflow threads regarding Abstract Factory vs Factory Method. I understand the intent of each pattern. However, I am not clear on the definition.

Factory Method defines an interface for creating an object, but lets subclasses decide which of those to instantiate. A factory method lets classes defer instantiation to subclasses.

By contrast, an Abstract Factory provides an interface for creating families of related or dependent objects without specifying their concrete classes.

-John Feminella

The Abstract Factory looks very similar to the Factory Method. I have drawn a few UML classes to illustrate my point.

Note:

  • The diagram are from www.yuml.com so they are not perfectly oriented. But its a free service :).
  • The diagrams may not be perfect. I am still learning the GoF design patterns.

Factory Method:

Factory Method

Abstract Factory (only 1 member):

Abstract Factory (only 1 member)

Abstract Factory (more members):

alt text

Questions:

  1. If the Abstract Factory has only one creator and one product, is it still the Abstract Factory pattern? (an interface for creating familes)
  2. Can the Factory Method concrete creator be created from an Interface or does it have to be from a class? (classes defer instantiations to subclasses)
  3. If the Abstract Factory can have only one creator and one product, is the only difference between the Abstract Factory and the Factory Method that the creator for the former is an Interface and the creator for the latter is a Class?

Answer

user295190 picture user295190 · Nov 18, 2010

Hope this helps. It describes the various types of factories. I used Head First Design Patterns as my reference. I used yuml.me to diagram.

Static Factory

Is a class with a Static Method to product various sub types of Product.

Static Factory

Simple Factory

Is a class that can produce various sub types of Product. (It is better than the Static Factory. When new types are added the base Product class does not need to be changed only the Simple Factory Class)

Simple Factoryt

Factory Method

Contains one method to produce one type of product related to its type. (It is better than a Simple Factory because the type is deferred to a sub-class.)

Factory Method

Abstract Factory

Produces a Family of Types that are related. It is noticeably different than a Factory Method as it has more than one method of types it produces. (This is complicated refer to next diagram for better real-life example).

Abstract Factory

Example From The .NET Framework

DbFactoriesProvider is a Simple Factory as it has no sub-types. The DbFactoryProvider is an abstract factory as it can create various related database objects such as connection and command objects.

Abstract Factory From .NET Framework ​​​