University of Cincinnati logo and link  
CinJUG: Design Patterns, October 16, 2006
 
 

Factory Method Pattern

UC ingot

Intent

“Define interface for creating an object, but let subclasses decide which class to instantiate.” - GoF

Motivation

Encapsulates knowledge of which subclass to create, and moves this out of the framework.

Applicability

Use Factory Method when:

  • A class can't 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 the helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

Structure

  • Product defines the interface of objects the factory method creates (MonthlyCommand).

  • ConcreteProduct implements the Product interface (Annuity, Employee, LifeInsurance).

  • Creator declares the factory method, which returns an object of type Product. 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 (used in my example).

  • Concrete Creator overrides the factory method to return an instance of ConcreteProduct. (Not used in my example.)

Consequences

  • Eliminates need to bind app-specific classes into code. Code only deals with Product interface.

  • May have to subclass Creator just to create a particular ConcreteProduct. Not in my case – my design is flexible.

  • Provides hooks for subclasses.

  • Connects parallel class hierarchies.

Implementation

  • Two Major Varieties:

    • Creator class is abstract and does not provide default implementation. Forces creation of subclasses that will create appropriate objects.

    • Creator class is concrete and does provide default implementation. Subclasses can override this default implementation, if needed.

  • Parameterized factory methods:

    • Factory method creates multiple kinds of products. Factory method takes a parameter that identifies the kind of object to create. All will share the Product interface.  (Used in my example.)

    • Can still override factory.

    • Language-specific variants and issues

  Behavioral Patterns - Command Pattern

 Cincinnati Java Users Group