Factory Method Pattern
Define an interface for creating an object, but let subclasses decide which class to instantiate.
Intent & Objective
Provide an interface for creating objects in a superclass, while allowing subclasses to alter the type of objects that will be created without modifying the client code.
"A shipping company defines a uniform order fulfillment process. Road logistics produces Trucks, Sea logistics produces Ships. The customer ordering delivery simply tracks the parcel."
"A central molding process produces toys, but specialized sub-factories override the mold step to output wooden blocks vs plastic action figures."
The Problem
Direct coupling between client code and concrete product classes via `new ConcreteProduct()`. If a new product type is needed, the entire client code must be rewritten.
The Solution
Replace direct object construction calls with calls to a special factory method. Subclasses can override this method to return different concrete instances conforming to a common product interface.
Key Participants & Architectural Roles
Code Samples (Traditional OOP vs Functional Programming)
Available in C++, Python, and JavaParadigm Contrast: Traditional OOP vs Functional / Data-Oriented
In OOP, Factory Method relies on subclassing and virtual methods. In Functional Programming, functions are first-class values: a "Factory" is simply a higher-order function or a dictionary mapping keys to pure constructor functions.
Advantages
- β Avoids tight coupling between creator and concrete products
- β Single Responsibility Principle: moves product creation code to one place
- β Open/Closed Principle: introduces new product types without breaking existing client code
Trade-offs
- β May require creating many subclasses just to instantiate a specific product class
When to Apply
- β When you do not know beforehand the exact types and dependencies of objects your code should work with
- β When you want to provide users of your library or framework with a way to extend its internal components
When to Avoid
- ! When the set of product classes is small, static, and unlikely to change