Factory Method

Intent

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Motivation

  • Suppose a text editor wants to manipulate (save, load, etc.) documents without knowing they types: JSON, XML, text, etc.

  • How can to create a new document without knowing its concrete type?

Diagram

Applicability

Use the Factory Method pattern when
  • a class cannot anticipate the class of objects it must create.

  • a class wants its subclasses to specify the objects it creates.

  • classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

Structure

Diagram

Participants

Product
  • defines the interface of objects the factory method creates.

ConcreteProduct
  • implements the Product interface.

Creator
  • declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.

  • may call the factory method to create a Product object.

  • the code may become more complicated: introduces a lot of new subclasses

ConcreteCreator (MyApplication)
  • overrides the factory method to return an instance of a ConcreteProduct.

Consequences

  • The code only deals with the Product interface: eliminates the need to bind application-specific classes into your code.

  • Provides hooks for subclasses.

  • Connects parallel class hierarchies.

Implementation Tradeoffs

  • Two variants:

    1. the Creator class is an abstract class and does not provide an implementation for the factory method

    2. the Creator is a concrete class and provides a default implementation for the factory method

  • Parameterized factory methods.

Authors and Date

  • «Design Patterns: Elements of Reusable Object-Oriented Software.» Erich Gamma, Richard Helm,Ralph Johnson, and John Vlissides. Addison Wesley. October 1994.