Design Patterns

Pattern 2 of 23, Creational family

Factory Method

Also known as: Virtual Constructor

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

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
  1. The client uses a concrete creator through the Logistics interface.
  2. RoadLogistics' factory method instantiates a Truck.
  3. The client works with a "Transport", without knowing the Truck class.
  4. Same client code, different creator.
  5. SeaLogistics overrides the factory method and produces a Ship.
  6. 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

factory-method.py 33 lines
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

factory-method.ts 27 lines
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

factory-method.java 20 lines
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#

factory-method.cs 21 lines
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

factory-method.php 24 lines
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

factory-method.go 21 lines
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.