Factory Method

creational

Defines an interface for creating objects, but lets subclasses decide which class to instantiate.

Intent

The Factory Method pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. It lets a class defer instantiation to subclasses.

Motivation

When a class cannot anticipate the type of objects it needs to create, or when a class wants its subclasses to specify the objects it creates, the Factory Method pattern is useful. It promotes loose coupling by eliminating the need to bind application-specific classes into the code.

Structure

The pattern involves a Creator class that declares the factory method, which returns an object of type Product. ConcreteCreator classes override the factory method to return an instance of a ConcreteProduct.

Participants

  • Product - defines the interface of objects the factory method creates
  • ConcreteProduct - implements the Product interface
  • Creator - declares the factory method
  • ConcreteCreator - overrides the factory method to return a ConcreteProduct

Pros

  • Eliminates the need to bind application-specific classes into the code
  • Provides hooks for subclasses
  • Connects parallel class hierarchies
  • Follows Open/Closed Principle

Cons

  • Can lead to a large number of subclasses
  • Clients might need to subclass the Creator class just to create a particular ConcreteProduct

Use Cases

GUI frameworks with different look-and-feel standards
Document editors with different document types
Data access layers with different database providers
Logistics applications with different transport methods

Implementation Tips

Considerations

  • Decide if the Creator class should provide a default implementation
  • Consider using parameters to specify the kind of product to create
  • Think about naming conventions for factory methods

Tips

  • Use descriptive names for factory methods like createProduct()
  • Consider making the factory method abstract to force subclasses to override it
  • Document what kind of objects the factory method creates

Interactive Code Editor