Factory Method is a creational design pattern that defines an interface for creating an object but lets subclasses decide which class to instantiate. Instead of calling a constructor directly with new, you call a factory method — and the subclass determines the concrete type.
ℹ️Core idea: delegate object creation to subclasses. The creator class declares the factory method; each concrete creator overrides it to produce a specific product.
The Problem It Solves
Imagine you're building a logistics app. Initially it only handles trucks. You hard-code new Truck() everywhere. Then the business needs sea shipping. Now you have to change every place that creates transport. Factory Method lets you isolate the creation logic so adding a new transport type requires only a new subclass.
Click to animate the creation flow ▶
🏭
Creator
declares createTransport()
→
🔧
Factory Method
overridden by subclass
→
📦
Concrete Creator
TruckLogistics
→
🚚
Product
Truck : Transport
Structure
Click a role to learn what it does
📐
Product
🚚
Concrete Product
🏭
Creator
🔧
Concrete Creator
Code Example
java
// Product interface
interface Transport {
void deliver();
}
// Concrete Products
class Truck implements Transport {
@Override
public void deliver() {
System.out.println("Delivering by land in a truck");
}
}
class Ship implements Transport {
@Override
public void deliver() {
System.out.println("Delivering by sea in a container ship");
}
}Step-by-Step: What Happens at Runtime
Click each step to see details
Config
1
Creator
2
planDelivery()
3
createTransport()
4
deliver()
5
When to Use Factory Method
Click to expand each scenario
❓
Unknown type at design time
🔌
Extending a library
♻️
Reusing existing objects
⚠️Trade-off: Factory Method may lead to many parallel subclass hierarchies — a ConcreteCreator for every ConcreteProduct. If the hierarchy grows large, consider Abstract Factory or Prototype instead.
Factory Method in the Java Standard Library
Click highlighted lines to see the pattern in action
java
1
// java.util.Collection — iterator() is a factory method
2
List<String> list = new ArrayList<>();
▼
3
Iterator<String> it = list.iterator();
▼
4
5
// java.nio.file.Files — static factory methods
6
Path path = Path.of("/tmp/file.txt");▼
7
8
// java.util.Calendar
9
Calendar cal = Calendar.getInstance();
▼
✅Key takeaway: Factory Method promotes the Open/Closed Principle — you can add new product types (new transport) without changing existing creator code (Logistics.planDelivery).