Factory Method and Abstract Factory compared

Ritratto di jdaemon

Factory Method (FM) and Abstract Factory (AF) are two of the main Design Patterns[0]. Both highly correlated, have several traits in common including:

  • The purpose to create objects, which is why FM and AF are classified as creational
  • The design feature of decoupling[1] the client class from implementation of factory classes of products[2]. In this way, the client is freed from knowing how the products are created

Usually in software design, the client creates a concrete implementation of AF Class or Creator Class of FM who is left to decide which objects to instantiate. When decide upon to use AF, its methods may be implemented either as FMs, as clones of Prototype Pattern or as get_instance() method of Singleton Pattern.

Structurally we can think of a FM as a family of interfaces each with a single builder method. Based only on this statement, a resulting implementation does not guarantee that it would be a FM rather than a simple case of AF.

The substantial difference between Factory Method and Abstract Factory is that

  • FM (also called Simple Factory) is a builder method implemented by any concrete subclass on their own
  • AF is a builder class (factory) implemented by a family of interfaces connected to each other

In terms of interactions between elements, FM has class scope and AF has object scope[3]; because the first focuses on (factory) method invoked from inside the class hierarchy, whereas the second focused on (factory) methods invoked from the outside the class hierarchy.


NOTES
[0] Design Pattern: general reusable solution to a commonly occurring problem within a given context in software design
[1] Decoupling: characteristic of entities that operate independently
[2] Products: objects to create
[3] Scope: Indicates whether the pattern specifies relations between classes or objects