design patterns ·
Factory Method
Defines an interface for creating an object but lets subclasses decide which class to instantiate.
Theory
Explanation
Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.
When a class needs to create objects but should not know exactly which class to instantiate, delegate the decision to subclasses via a factory method.
The creator base class declares an abstract createProduct() factory method. Each concrete subclass overrides it to return a specific product. The base class uses the factory method result without knowing the concrete type.
When to use
When the exact type of object to create is not known until runtime. When subclasses should control what gets created - UI libraries, document parsers, payment gateways.
When not to
When there is only one product type, or when the product type can be passed as a constructor parameter instead.
Key insights
- The factory method is in the creator, not a separate factory class
- Separates product construction from business logic in the creator
- Enables the creator to be unit-tested with a mock product via subclassing
- Often paired with the Template Method pattern - factory method is a hook