design patterns · creational

Factory Method

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

easycreational0.5h
Ask GPTConfidence

Pattern

Overview

Intent

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

Real-World Analogy

A logistics company declares it will deliver cargo but subclasses (RoadLogistics, SeaLogistics) decide whether to use trucks or ships.

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.

Participants

CreatorConcreteCreatorProductConcreteProduct

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