Concept Explanation
Creational patterns answer one question: who decides which object gets built, and how?
Factory hides which class is created. Builder tames constructors with too many parameters.
The Factory Method
Without it, new scatters concrete class names throughout your code:
// Callers now depend on every payment implementation
if (type.equals("card")) processor = new CardProcessor();
else if (type.equals("paypal")) processor = new PayPalProcessor();
With a factory, that decision lives in exactly one place:
public interface PaymentProcessor {
Receipt charge(BigDecimal amount);
}
public class PaymentProcessorFactory {
public static PaymentProcessor forMethod(PaymentMethod method) {
return switch (method) {
case CARD -> new CardProcessor();
case PAYPAL -> new PayPalProcessor();
case UPI -> new UpiProcessor();
};
}
}
PaymentProcessor p = PaymentProcessorFactory.forMethod(order.getMethod());
Receipt receipt = p.charge(order.getTotal());
Adding a fourth method touches one file, and callers never change.
In Spring you often get this for free — inject Map<String, PaymentProcessor> and Spring populates it with every implementing bean, keyed by bean name.
The Builder
The problem it solves — the telescoping constructor:
new Pizza("large", true, false, true, true, false, 2);
Nobody can read that, and swapping two booleans compiles fine while producing the wrong pizza.
public class Pizza {
private final String size;
private final boolean cheese;
private final boolean mushrooms;
private final int extraToppings;
private Pizza(Builder b) { // private: only the builder constructs it
this.size = b.size;
this.cheese = b.cheese;
this.mushrooms = b.mushrooms;
this.extraToppings = b.extraToppings;
}
public static Builder builder() { return new Builder(); }
public static class Builder {
private String size = "medium"; // sensible defaults
private boolean cheese;
private boolean mushrooms;
private int extraToppings;
public Builder size(String s) { this.size = s; return this; }
public Builder cheese() { this.cheese = true; return this; }
public Builder mushrooms() { this.mushrooms = true; return this; }
public Builder extraToppings(int n){ this.extraToppings = n; return this; }
public Pizza build() {
if (extraToppings > 5)
throw new IllegalArgumentException("Max 5 extra toppings");
return new Pizza(this); // validate before constructing
}
}
}
Pizza p = Pizza.builder()
.size("large")
.cheese()
.extraToppings(2)
.build();
Self-documenting, order-independent, and the result is immutable.
You already use this pattern constantly: StringBuilder, Stream.Builder, and Spring's RestTemplateBuilder.
When to Use Which
| Situation | Pattern |
|---|---|
| The concrete type depends on input | Factory |
| Many optional parameters | Builder |
| More than three constructor parameters | Builder |
| Object must be immutable after creation | Builder |
| Two or more implementations of an interface | Factory |
Common Mistakes
- A factory returning a concrete type: Return the interface, or you have gained nothing.
- A builder with no validation in
build(): That method is your last chance to reject an invalid object. - Patterns for their own sake: A class with two fields needs a constructor, not a builder.
- Mutable objects from a builder: Setters after
build()destroy the immutability guarantee.
Best Practices
- Return interfaces from factories so callers stay decoupled.
- Validate in
build(), throwing before an invalid object can exist. - Consider Lombok's
@Builderfor boilerplate-free builders in application code. - Records over builders when every field is required and there are few of them.
Practice Exercises
- The Notification Factory: Build a factory returning
Email,Sms, orPushsenders behind one interface. - The Builder: Convert a seven-parameter constructor into a builder with defaults and validation.
- The Spring Map: Inject
Map<String, PaymentProcessor>into a service and select an implementation by key at runtime.