Creational 1 — Factory
In one line
Centralize object creation behind one method so callers depend on the created type's contract, not its construction logic.
Think of it like this
A pizza counter. You say 'one Margherita' and get a pizza. You don't knead the dough or know the recipe; the kitchen (factory) decides how to make it.
Key ideas
- 01
Problem solved: callers scattered with if/else constructor logic; adding a type means touching many files.
- 02
Factory Method: one abstract create() per hierarchy. Abstract Factory: a family of related products.
- 03
In interviews, a simple static factory (sometimes over 'abstract factory') is usually the right size.
- 04
Java note: Calendar.getInstance(), NumberFormat.getInstance(), List.of() and Executors.newFixedThreadPool() are static factory methods.
- 05
Registry variant: a Map<Type, Supplier<Product>> lets new types register themselves, so even the factory stays closed to modification.
Java / Spring map
- →
Spring's @Bean methods / FactoryBean are factories; @Configuration classes are factory classes.
Code & diagrams
Simple factory: zero switch statements in callers.
public interface Vehicle { String type(); }
public class Car implements Vehicle { public String type() { return "CAR"; } }
public class Bike implements Vehicle { public String type() { return "BIKE"; } }
public class Truck implements Vehicle { public String type() { return "TRUCK"; } }
public final class VehicleFactory {
public static Vehicle create(String type) {
return switch (type.toUpperCase()) {
case "CAR" -> new Car();
case "BIKE" -> new Bike();
case "TRUCK" -> new Truck();
default -> throw new IllegalArgumentException("unknown: " + type);
};
}
}
// Parking lot gate: Vehicle v = VehicleFactory.create(plate); // new vehicle → one line.Explain without notes
Which OCP violation does the factory prevent?
Practice
Add 'BUS' and 'EV' variants to the factory without touching callers.
Trade-offs
- ↔
A factory hides which concrete class is used — good for decoupling, bad when callers need type-specific behavior.
Completion checklist
I can explain intent + one real use.
I can distinguish a simple static factory, Factory Method, and Abstract Factory.