Lesson 25 / 38
Factory Pattern
Hide object construction behind a method or class so callers depend on an interface, not a concrete constructor, making it easy to swap implementations.
Decouple 'what' from 'how it's built'
A factory method returns an interface type while deciding internally which concrete class to instantiate. Callers never call new ConcreteThing() directly, so a new implementation can be added without touching client code.
A payment factory
The factory centralises the if/switch that picks an implementation — that logic exists exactly once instead of being copy-pasted at every call site.
interface PaymentGateway { void charge(int cents); }
class PaymentGatewayFactory {
static PaymentGateway create(String provider) {
return switch (provider) {
case "stripe" -> new StripeGateway();
case "paypal" -> new PayPalGateway();
default -> throw new IllegalArgumentException(provider);
};
}
}
PaymentGateway gw = PaymentGatewayFactory.create("stripe");
gw.charge(500);