Object-Oriented Programming

Design Pattern: Factory Method

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Factory Method

Factory Method

  • Class Creational Pattern

  • A class pattern that defines an interface for creating an object, but let subclasses decide which class to instantiate, lets a class defer instantiation to subclasses.

  • AKA: Virtual Constructor

Factory Method

  • Frameworks use abstract classes to define and maintain relationships between objects
  • Also responsible for creating these objects
  • However, knowledge of what type of object to create may not be in the framework

Factory Method: Motivation

Factory Method: Applicability

  • Classes can’t anticipate the class of objects it must create
  • Classes want 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

Factory Method: Structure

Factory Method: Product Participants

  • Product (e.g., Document)
    • Defines the interface of objects the factory method creates
  • ConcreteProduct (e.g., MyDocument)
    • Implements the Product interface

Factory Method: Creator Participants

  • Creator (e.g., Application)
    • 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.
  • ConcreteCreator (e.g., MyApplication)
    • Overrides the factory method to return an instance of a ConcreteProduct.

Factory Method: Collaborations

  • Creator relies on subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct

Factory Method: Consequences

  • Code only deals with Product interfaces, so can work with any user-defined ConcreteProduct classes
  • Does require a client to subclass Creator for each unique ConcreteProduct
  • Can define a non-abstract default, e.g., CreateFileDialog, that subclasses can override if needed

Factory Method: Parallel Class Hierarchies

Implementation: Maze

Implementation: Factory

Implementation: Using Factory

Implementation: Subclassing

UML

Lazy Initialization

Known Uses

Factory methods pervade toolkits and frameworks

Related Patterns

  • Abstract Factory
    • Often implemented with factory methods
  • Template Methods
    • Typically called to create a proper object