Simple Factory (Static Factory)
The problem
Checkout has to charge customers via card, PayPal, or gift card. If checkout code does
new CardProcessor() / new PayPalProcessor() directly, every place that takes a payment knows
about every concrete class – and adding a payment method means hunting down all of them.
The pattern
Creation is centralised behind one static factory method. Callers name what they want
(a PaymentMethod), not how it’s built:
PaymentProcessor processor = PaymentProcessors.forMethod(PaymentMethod.PAYPAL);
PaymentReceipt receipt = processor.process(total);
The concrete classes are private nested types – clients cannot couple to them even if they try.
Not the GoF “Factory Method”
This shape is often loosely called “Factory Method”, but the Gang of Four pattern of that name is
something more specific: an abstract creator class whose subclasses override a method to
decide which product to build. What this package shows – one static method with a switch – is
the simple factory (Effective Java’s “static factory method”, Item 1), and it’s what working
Java code almost always uses. The true GoF shape survives mostly inside frameworks, where the
framework owns the algorithm and your subclass supplies the objects (e.g. overriding a
createXyz() hook). If an interviewer or a design review says “Factory Method”, it’s worth
checking which of the two they mean.
Benefits
- Decoupling – checkout depends only on the
PaymentProcessorinterface; concrete classes can be renamed, replaced, or rewritten freely. - One package to change – supporting a new payment method means adding an enum constant and a
switchcase, both in this package; because theswitchover the enum is exhaustive, the compiler flags every spot you forget. Callers don’t change at all. - Hidden implementation choice – the factory may return a new instance, a cached one, or a subtype; callers can’t tell and don’t care.
Seen in the wild
List.of(), Optional.of(), Files.newBufferedReader(), JDBC’s DriverManager.getConnection(),
Executors.newFixedThreadPool(). Spring’s FactoryBean and servlet/framework createXyz() hooks
are where the GoF subclass-driven variant still earns its keep.
Implementation
PaymentProcessors– the factory; the concrete processors are itsprivatenested classes.PaymentProcessor– the interface callers depend on.PaymentMethod– the enum naming what callers can ask for.PaymentReceipt– the result type.