Factory Method

Category

Creational pattern

Problem

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

Solution

  • Define an abstract base class with a factory method that returns an object of the base class type
  • Subclasses override the factory method to return instances of their specific concrete classes
  • Client code calls the factory method on the base class, never instantiating concrete classes directly

Structure

  • Product: The interface for objects the factory method creates
  • ConcreteProduct: Concrete implementations of the Product interface
  • Creator: Abstract class declaring the factory method
  • ConcreteCreator: Overrides the factory method to return a ConcreteProduct

Key Benefits

  • Loose coupling — Client code depends on abstractions, not concrete classes
  • Open/Closed Principle — New product types can be added by creating new creators, without modifying existing code
  • Centralized creation logic — All object creation happens in one place per hierarchy

Trade-offs

  • Can lead to deep class hierarchies as new product types are added
  • May require refactoring when new types are introduced to existing code
  • Adds abstraction overhead for simple scenarios

When to Use

  • A class doesn’t know which class of objects it must create in advance
  • A class wants its subclasses to specify the objects it creates
  • You want to delegate responsibility to one of several helper subclasses

Examples