Factory Method
Intent
Defines an interface for creating an object but lets subclasses decide which class to instantiate.
Problem
Your logistics app only knows trucks. Adding ships means touching every place that calls new Truck().
Solution
Replace direct construction with a call to a factory method that subclasses override. Client code works with the product interface only.
Real-world analogy
A logistics company decides whether a shipment travels by truck or by ship. The customer only asks for delivery.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1Product — Product declares the interface common to everything the creator and its subclasses can produce.
- 2ConcreteProductA — Concrete Products are the different implementations of that interface.
- 3Creator — Creator declares the factory method that returns a Product. Its main job is still business logic that uses the product.
- 4ConcreteCreatorA — Concrete Creators override the factory method to return a different product type.
Try it
logistics.plan()
Code example
public interface ITransport { string Deliver(); }
public class Truck : ITransport { public string Deliver() => "by road"; }
public class Ship : ITransport { public string Deliver() => "by sea"; }
public abstract class Logistics
{
protected abstract ITransport CreateTransport(); // factory method
public string Plan() => CreateTransport().Deliver();
}
public class RoadLogistics : Logistics
{
protected override ITransport CreateTransport() => new Truck();
}
public class SeaLogistics : Logistics
{
protected override ITransport CreateTransport() => new Ship();
}Applicability
Use Factory Method when you don't know in advance the exact types your code will work with.
Use Factory Method when you want users of your library to extend its internal components.
Use Factory Method when you want to reuse existing objects instead of rebuilding them.
How to implement
- Make all products follow a common interface
- Add an empty factory method to the creator, returning the product interface
- Replace constructor calls in the creator with calls to the factory method
- Create a creator subclass for each product type and override the factory method
Pros and cons
Pros
- Avoids tight coupling between creator and concrete products
- Single Responsibility: creation code in one place
- Open–Closed: new products without breaking clients
Cons
- Can add many subclasses
Relations with other patterns
Check yourself
A document editor opens .docx, .pdf and .md files, and plugin authors must add new formats by subclassing.
Saved in this browser only. Part of Creational patterns (0/5), Hands-on: patterns with live demos (0/5).