Factory Method
Also known as: Virtual Constructor
Define an interface for creating an object, but let subclasses decide which concrete class to instantiate.
- 6 animated steps
- 6 languages
- Creational patterns
The problem
Your logistics app only handles trucks: new Truck() is everywhere. Adding sea transport forces you to change all the code that creates and uses transports.
The solution
Replace direct new calls with a "factory" method (createTransport()) defined in a creator class and overridden by each subclass. Client code only works with the Transport interface.
The pattern in action
- Client
- Key role of the pattern
- Object
- Data or state
- The client uses a concrete creator through the Logistics interface.
- RoadLogistics' factory method instantiates a Truck.
- The client works with a "Transport", without knowing the Truck class.
- Same client code, different creator.
- SeaLogistics overrides the factory method and produces a Ship.
- A new transport mode added without touching the client code.
An analogy
A restaurant franchise: headquarters defines "make a burger", and each local restaurant decides on the exact recipe.
When to use it
- The exact type of the objects is not known in advance
- Give users of a library / framework an extension point
- Reuse existing objects (pool) instead of creating new ones
Pros and cons
Pros
- Decouples the creator from concrete products
- Open/Closed: new product = new subclass
- Centralized creation (SRP)
Cons
- Proliferation of subclasses
- Can be overkill when a plain constructor is enough
Implementations
The same example, written idiomatically in each language.
Factory Method in Python
from abc import ABC, abstractmethod
class Transport(ABC):
@abstractmethod
def deliver(self) -> str: ...
class Truck(Transport):
def deliver(self): return "Delivery by road"
class Ship(Transport):
def deliver(self): return "Delivery by sea"
class Logistics(ABC):
@abstractmethod
def create_transport(self) -> Transport: ... # the factory method
def plan_delivery(self) -> str:
return self.create_transport().deliver()
class RoadLogistics(Logistics):
def create_transport(self): return Truck()
class SeaLogistics(Logistics):
def create_transport(self): return Ship()
print(SeaLogistics().plan_delivery())
Factory Method in TypeScript
interface Transport {
deliver(): string;
}
class Truck implements Transport {
deliver() { return "Delivery by road"; }
}
class Ship implements Transport {
deliver() { return "Delivery by sea"; }
}
abstract class Logistics {
protected abstract createTransport(): Transport; // factory method
planDelivery() {
return this.createTransport().deliver();
}
}
class RoadLogistics extends Logistics {
protected createTransport() { return new Truck(); }
}
class SeaLogistics extends Logistics {
protected createTransport() { return new Ship(); }
}
console.log(new SeaLogistics().planDelivery());
Factory Method in Java
interface Transport { String deliver(); }
class Truck implements Transport { public String deliver() { return "Delivery by road"; } }
class Ship implements Transport { public String deliver() { return "Delivery by sea"; } }
abstract class Logistics {
protected abstract Transport createTransport(); // factory method
public String planDelivery() {
return createTransport().deliver();
}
}
class RoadLogistics extends Logistics {
@Override protected Transport createTransport() { return new Truck(); }
}
class SeaLogistics extends Logistics {
@Override protected Transport createTransport() { return new Ship(); }
}
Factory Method in C#
interface ITransport { string Deliver(); }
class Truck : ITransport { public string Deliver() => "Delivery by road"; }
class Ship : ITransport { public string Deliver() => "Delivery by sea"; }
abstract class Logistics
{
protected abstract ITransport CreateTransport(); // factory method
public string PlanDelivery() => CreateTransport().Deliver();
}
class RoadLogistics : Logistics
{
protected override ITransport CreateTransport() => new Truck();
}
class SeaLogistics : Logistics
{
protected override ITransport CreateTransport() => new Ship();
}
Factory Method in PHP
interface Transport { public function deliver(): string; }
class Truck implements Transport { public function deliver(): string { return 'Delivery by road'; } }
class Ship implements Transport { public function deliver(): string { return 'Delivery by sea'; } }
abstract class Logistics
{
abstract protected function createTransport(): Transport; // factory method
public function planDelivery(): string
{
return $this->createTransport()->deliver();
}
}
class RoadLogistics extends Logistics
{
protected function createTransport(): Transport { return new Truck(); }
}
class SeaLogistics extends Logistics
{
protected function createTransport(): Transport { return new Ship(); }
}
Factory Method in Go
type Transport interface{ Deliver() string }
type Truck struct{}
func (Truck) Deliver() string { return "Delivery by road" }
type Ship struct{}
func (Ship) Deliver() string { return "Delivery by sea" }
// Go has no inheritance: the factory is an injected function
type Logistics struct {
CreateTransport func() Transport
}
func (l Logistics) PlanDelivery() string {
return l.CreateTransport().Deliver()
}
var Road = Logistics{CreateTransport: func() Transport { return Truck{} }}
var Sea = Logistics{CreateTransport: func() Transport { return Ship{} }}
Frequently asked questions
What is the Factory Method design pattern?
Define an interface for creating an object, but let subclasses decide which concrete class to instantiate. Replace direct new calls with a "factory" method (createTransport()) defined in a creator class and overridden by each subclass. Client code only works with the Transport interface.
When should you use the Factory Method pattern?
The exact type of the objects is not known in advance; Give users of a library / framework an extension point; Reuse existing objects (pool) instead of creating new ones.
What are the pros and cons of the Factory Method pattern?
Pros: Decouples the creator from concrete products; Open/Closed: new product = new subclass; Centralized creation (SRP). Cons: Proliferation of subclasses; Can be overkill when a plain constructor is enough.