Factory Method moves one decision, which class to instantiate, out of the code that uses the object. A base class (the creator) does its real work against a product interface, and gets the product by calling one of its own overridable methods, the factory method. Each subclass overrides that method to return a different concrete product, so the base class never writes new for a concrete product class. It is one of the most common patterns in frameworks, and the word "factory" is also used for a looser idea, the simple factory, which this lesson separates from it.
Think of it like
A franchise kitchen
A burger chain writes one operations manual for every branch: take the order, cook the patty, assemble, serve. One step says only "use the local bun". The Mumbai branch bakes a pav, the Paris branch a brioche. Head office never edits the manual when a new country opens; the new branch supplies its own bun step. The manual is the creator's template code, "use the local bun" is the factory method, each branch is a concrete creator, and the bun is the product.
The problem
A logistics app started with road deliveries only. Logistics.plan() holds the delivery logic (count the trip, hand the cargo to a vehicle) and, in the middle of it, creates the vehicle itself with new Truck(). This is the Before version in the visualizer above.
interface Vehicle {
deliver(cargo: string): string;
}
class Truck implements Vehicle {
deliver(cargo: string): string {
return `${cargo} by truck`;
}
}
class Logistics {
private trips = 0;
plan(cargo: string): string {
const t = new Truck(); // the concrete class is named right here
this.trips++;
return t.deliver(cargo);
}
}
const app = new Logistics();
app.plan("tea"); // "tea by truck"Then the business adds sea freight. The delivery logic is the same; only the vehicle differs. But the only way to get a Ship into plan() is to open Logistics and add a choice:
class Logistics {
private trips = 0;
constructor(private mode: string) {}
plan(cargo: string): string {
let t: Vehicle;
switch (this.mode) {
case "road":
t = new Truck();
break;
case "sea":
t = new Ship();
break;
default:
throw new Error(this.mode);
}
this.trips++;
return t.deliver(cargo);
}
}- The class with the business logic changes for every new product. Air freight, drones and rail each mean another
caseinsideplan(), the method every delivery runs through, and another round of testing for all of them. Logisticsdepends on every concrete vehicle. It importsTruck,Shipand whatever comes next, so it can never be closed for modification, which is what the open/closed principle in SOLID Principles asks for.- Nobody else can add a vehicle. A team or a plugin that wants its own transport has to get its change into
Logisticsitself. - The switch repeats. Cost estimates, tracking and receipts soon want the same
switch (mode), and each copy must be updated together.
The pattern
Intent (from the Gang of Four book): define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. The book also calls it a virtual constructor.
- Product (
Vehicle) - The interface the created objects share. The creator's code only ever talks to this type.
- Concrete product (
Truck,Ship) - The real classes being created. Each implements the product interface.
- Creator (
Logistics) - The class that does the real work (
plan()) and declares the factory method. It is usually abstract, but it may also give the factory method a default implementation. - Factory method (
createVehicle()) - An overridable method that returns a product. The creator calls it on
thiswherever it needs a new product. - Concrete creator (
RoadLogistics,SeaLogistics) - A subclass that overrides the factory method to return one concrete product. Often that override is the whole subclass.
abstract class Logistics {
private trips = 0;
// Shared logic, written once. It needs a vehicle but never names one.
plan(cargo: string): string {
const t: Vehicle = this.createVehicle(); // the factory method
this.trips++;
return t.deliver(cargo);
}
// Subclasses decide which Vehicle to make.
protected abstract createVehicle(): Vehicle;
}
class RoadLogistics extends Logistics {
protected createVehicle(): Vehicle {
return new Truck();
}
}
const road: Logistics = new RoadLogistics();
road.plan("tea"); // "tea by truck"Two hierarchies run side by side: creators on one side, products on the other, and each concrete creator is paired with the product it makes. The creator depends only on the Vehicle interface; the single new Truck() lives in RoadLogistics. The client chooses a concrete creator, and that choice decides the product, without the client or plan() ever mentioning Truck.
What the visualizer shows
- Class diagram: products on the left (
VehicleandTruck), creators on the right (LogisticsandRoadLogistics), and a dashed «create» arrow from each concrete creator to the product it makes. Whenplan()callscreateVehicle(), the abstractLogisticslights violet (it declares the method) whileRoadLogisticslights amber (its override runs). When a truck is created, the «create» arrow lights green. - Objects at runtime:
road : RoadLogisticswith itstripscounter, and each truck it makes. The call tocreateVehicle()loops back intoroaditself, because the factory method is called onthis. Eachplan()call makes a new truck, sotruck2appears on the second delivery. - Sequence of calls:
plan("tea")arrives atroad,roadcalls itself, a «create» message makestruck, the truck comes back as the return value, and only then doesdeliver("tea")go to it.
Press Play in the visualizer at the top of the page, or step with the arrow buttons: it really runs the classes in the code panel. The Before / With Factory Method toggle switches between the version where plan() says new Truck() and the pattern. Add sea applies the change request to whichever version is shown: changed classes get a badge (new class, or edited +13 −1), and the Change request panel beside the code counts what each version had to change. On a phone, the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Pick a concrete creator
With With Factory Method selected, the client runs
new RoadLogistics(). The objectroadappears withtrips = 0, inherited fromLogistics. The client never mentionsTruck: choosing road logistics is choosing the truck. - 2
Call the shared logic
road.plan("tea").RoadLogisticshas noplan()of its own, so the code in the abstractLogisticsruns. - 3
The base class calls down
plan()needs a vehicle, so it callsthis.createVehicle(). The method is declared abstract inLogistics; the object is aRoadLogistics, so its override runs. - 4
The subclass creates the product
RoadLogistics.createVehicle()runsnew Truck(). The objecttruckappears and travels back toplan()as the return value. - 5
Use the product through its interface
plan()holds the truck only as aVehicle. It counts the trip (tripsbecomes 1) and callst.deliver("tea"), which returns"tea by truck". - 6
Every call creates again
road.plan("salt")runs the same path and the factory method makestruck2. Whether to reuse one instance instead is the factory method's own decision (see Lazy creation under Variations). - 7
Add sea (change request)
With Add sea applied, the client creates
sea, aSeaLogistics, and callssea.plan("rice"). The very sameplan()runs, the call down lands inSeaLogistics.createVehicle(), and the result is"rice by ship".
Before and after
Without the pattern
plan()names the concrete vehicle (new Truck()) inside the delivery logic- A second vehicle needs a
modefield and aswitchinplan() Logisticsdepends on every concrete vehicle class- Only someone who can edit
Logisticscan add a vehicle - Fewer classes; fine while there is only ever one vehicle
With Factory Method
plan()works only with theVehicleinterface- Each vehicle comes with a small creator subclass that makes it
- Adding a vehicle adds two classes and edits none
plan()is written and tested once for every vehicle- Costs a parallel creator hierarchy: one subclass per product
| Change request: add sea | Before | With Factory Method |
|---|---|---|
| Existing classes edited | 1 (Logistics) | 0 |
| New classes | 1 (Ship) | 2 (Ship, SeaLogistics) |
| Lines changed in existing classes | 14 (+13 −1) | 0 |
The pattern does not save classes: it adds one more than the switch does. What it saves is the edit. Without it, the 14 changed lines (a constructor, a let, and the switch replacing const t = new Truck()) land in the class every delivery goes through. With it, the only code that changes is new code, and plan() keeps working unchanged. In both versions the client gains lines, because something has to say "use the sea".
Variations
Simple factory (not the GoF pattern)
Most code that people call "a factory" is a simple factory: one function or static method that takes a key and returns a product, with the switch inside it. It is not Factory Method, because no subclass overrides anything; it is a helpful refactoring that gathers every new in one place, so the rest of the code depends on the interface. The second implementation below is a simple factory backed by a registry.
| Simple factory | Factory Method | |
|---|---|---|
| Shape | One function or static method with a conditional | An overridable method on a creator class |
| Who picks the product | The factory, from an argument | The subclass, by overriding |
| Adding a product | Edit the factory (or add a registry entry) | Add a product and a creator subclass |
| Typical use | Hide constructors behind one entry point | A framework or base class that must create objects it cannot know about |
Parameterized factory method
The GoF book also describes a factory method that takes a parameter naming the kind of product. A subclass overrides it to handle the kinds it knows and calls super for the rest: if (mode === "sea") return new Ship(); return super.createVehicle(mode);. It can add or change products without repeating the parent's cases.
Static factory methods
Effective Java (Item 1) recommends to "consider static factory methods instead of constructors": a static method such as List.of(1, 2, 3), Integer.valueOf(42) or Optional.empty() that returns an instance. Compared with a constructor it has a name, it need not create a new object each time (Integer.valueOf returns cached instances for values from −128 to 127), and it can return any subtype of its declared return type, chosen at runtime. These are simple factories, not GoF Factory Method, since a static method cannot be overridden. Common names follow a convention: from, of, valueOf, getInstance, newInstance, create.
| Variation | How it works | Use it when |
|---|---|---|
| Default implementation | The creator's factory method returns a sensible product; subclasses override only when they need another | Most users are happy with the default, as with framework hooks |
| Factory with a registry | A map from a key to a constructor or supplier; plugins register new entries at startup | New products arrive from configuration or plugins, without subclassing or editing a switch |
| Lazy creation | An accessor calls the factory method the first time and caches the result | The product is expensive and one per creator is enough |
| Factory function passed in | The creator receives a () => Vehicle instead of being subclassed | You prefer composition to inheritance; this is Strategy for creation |
| Parallel hierarchies | A product family member makes its matching partner, e.g. a shape makes its own drag handler | Two hierarchies must stay paired |
In real code
| Where | Factory method | What it creates |
|---|---|---|
| Java collections | Collection.iterator() (declared by Iterable) | Each collection returns its own Iterator class; a for-each loop works with any of them through the Iterator interface. The GoF book's Iterator chapter calls CreateIterator() a factory method |
| JDBC | Connection.createStatement() | Each database driver's Connection returns its own Statement implementation |
| Application frameworks | Application.CreateDocument(), the GoF book's motivating example | A framework handles opening and saving; each application subclass says which Document class to create |
java.util.Calendar | Calendar.getInstance() | A calendar for the default locale and time zone, usually a GregorianCalendar; callers see only Calendar |
java.text.NumberFormat | NumberFormat.getInstance(), getCurrencyInstance() | A locale-specific formatter (typically a DecimalFormat) behind the abstract NumberFormat type |
| Java core types | List.of, Integer.valueOf, Optional.of | Immutable lists, cached boxed integers and optionals, with no public constructor call needed |
In application code, look for an abstract base class with a create...() or make...() hook: a report generator whose subclasses create the exporter, a game level that creates its own enemies, a test base class whose subclasses supply the object under test. The same shape appears in Iterator (each collection creates its iterator) and is the building block of Abstract Factory.
When to use it, and when not to
Reach for Factory Method when
- A base class or framework has shared logic that must create objects it cannot know in advance
- Subclasses, plugins or other teams should add products without editing the base class
- You already have a creator hierarchy and each subclass pairs with one product
- You want tests to substitute a fake product by overriding one method
Keep it simpler when
- There is one product and no sign of a second one (YAGNI)
- You would create a subclass only to override the factory method; a simple factory, a registry or a factory function passed in is lighter
- The product is chosen per call from data (that is a parameter or a registry, not a subclass)
- Construction is complex step by step (that is Builder)
Factory Method vs similar patterns
Every creational pattern hides a new. Ask what is being created (one object, a family, a complex object, a copy) and who decides the class (a subclass, an argument, a factory object, an existing instance).
| Pattern | What it creates | Who decides the class | Built with |
|---|---|---|---|
| Factory Method | One product | A subclass, by overriding a method | Inheritance: the creator calls its own hook |
| Simple factory | One product | The factory, from a key or argument | One function or static method with a conditional or a map |
| Abstract Factory | A family of related products that must match | The factory object the client was given | Composition: an object with several factory methods |
| Builder | One complex object, step by step | The builder and the steps the client calls | A separate object that assembles, then build() |
| Prototype | A copy of an existing object | Whichever prototype instance you clone | A clone() method on the product |
| Template Method | Nothing; it varies steps of an algorithm | A subclass, by overriding steps | Inheritance; Factory Method is often one of its steps |
Implementation
The visualizer's scenario as a complete program: an abstract Logistics creator with shared plan() logic and an abstract createVehicle() factory method, road and sea creators, and the Vehicle products they make. The client code works with Logistics only.
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def deliver(self, cargo: str) -> str: ...
class Truck(Vehicle):
def deliver(self, cargo: str) -> str:
return f"{cargo} by truck"
class Ship(Vehicle):
def deliver(self, cargo: str) -> str:
return f"{cargo} by ship"
class Logistics(ABC):
"""The creator: shared logic plus one overridable creation step."""
def __init__(self) -> None:
self.trips = 0
def plan(self, cargo: str) -> str:
vehicle = self.create_vehicle() # the factory method
self.trips += 1
return vehicle.deliver(cargo)
@abstractmethod
def create_vehicle(self) -> Vehicle: ...
# Concrete creators: each one only decides which product to make.
class RoadLogistics(Logistics):
def create_vehicle(self) -> Vehicle:
return Truck()
class SeaLogistics(Logistics):
def create_vehicle(self) -> Vehicle:
return Ship()
def ship(logistics: Logistics, cargo: str) -> None:
"""Client code: depends on Logistics, never on Truck or Ship."""
print(logistics.plan(cargo))
if __name__ == "__main__":
road = RoadLogistics()
ship(road, "tea") # tea by truck
ship(road, "salt") # salt by truck
ship(SeaLogistics(), "rice") # rice by ship
print(road.trips) # 2Key takeaways
- Factory Method lets a base class do its work with a product interface while subclasses decide which concrete product to create, by overriding one method.
- The creator calls the factory method on
this: the base class calls down into the subclass, the same mechanism as Template Method. - Adding a product adds classes instead of editing them. In the visualizer's "Add sea" request: 0 existing classes edited with the pattern, versus
Logisticsedited by 14 lines without it. - A function or static method with a switch is a simple factory, not Factory Method. Static factories like
List.ofandInteger.valueOfare a different, also useful, idea. - The price is a creator subclass per product. When a subclass would hold nothing but the factory method, a registry or a factory passed in is lighter.
Common pitfalls
- Calling the factory method from the creator's constructor: C++ runs the base version (or crashes on a pure virtual), and Java runs the override before the subclass's fields are set.
- Leaking the concrete type: a creator that casts the product back to
Truck, or checksinstanceof, has rebuilt the dependency the pattern removed. - Calling every
switchthat returns objects "Factory Method" in an interview. Name it a simple factory and explain the difference. - Creating a subclass hierarchy only to pick a class, when one registry or one constructor parameter would do: more classes, same flexibility.
Interview tips
- Draw the four roles (Product, Concrete Product, Creator, Concrete Creator) and point at the one line the pattern moves:
new Truck()leavesplan()and goes intoRoadLogistics.createVehicle(). - Expect "Factory Method vs Abstract Factory vs simple factory". Answer with the unit of variation: an overridden method, a factory object for a family, or a function with a switch.
- In LLD rounds (parking lot vehicles, notification channels, document exporters) a simple factory or registry is usually the right first step; mention Factory Method when a base class with shared logic must create objects that subclasses choose.
Real-world applications
- Frameworks whose base classes create objects that applications customize: documents in desktop app frameworks, views and controllers in UI toolkits.
- Collections that each create their own iterator (
iterator()in Java,__iter__in Python). - Database drivers that create their own statements and result sets behind standard interfaces (JDBC
createStatement()). - Locale-aware formatters and calendars returned by static factories (
NumberFormat.getInstance(),Calendar.getInstance()). - Test base classes whose subclasses supply the object under test or a fake collaborator.
Test yourself
In the logistics example, which participant decides that a Ship is created?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.