Catalog / Creational Patterns / Factory Method Pattern
CREATIONAL

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.

πŸ‘₯ Real-World Human Analogies & Social Roles
2 Intuitive Scenarios
Logistics Fleet Dispatcher Supply Chain Operations

"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."

Toy Mold Factory Manufacturing Assembly

"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

Product Interface
Declares the interface of objects created by the factory method
Concrete Products
Different implementations of the product interface
Creator (Abstract)
Declares factory method returning an object of type Product
Concrete Creators
Overrides factory method to return an instance of a Concrete Product

Code Samples (Traditional OOP vs Functional Programming)

Available in C++, Python, and Java

Paradigm 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