Skip to the content.

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

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

Example test

PaymentProcessorsTest