Patterns Worth Knowing
Loading
Loading
Patterns Worth Knowing
Factory Method, Abstract Factory, Builder and Singleton — mostly about not scattering `new` through your code.
By the end of this chapter
**Problem.** Deciding which concrete type to construct is scattered across the codebase, so adding a type means finding every `new`.
**Shape.** One place — a method or a small class — takes the inputs and returns the right implementation behind a shared interface. Callers ask for what they need and never name the concrete type.
**When it earns its keep.** Three or more implementations, chosen at runtime from data. **When it does not.** One implementation. A factory that returns the only class that exists is indirection with no payoff, and it will still be there in three years.
The same idea for a *family* of related types that must be consistent with each other — a set of widgets that must all be the same theme, or a set of storage adapters that must all target the same backend. The extra machinery only pays off when mixing families is a real bug you are preventing.
**Problem.** A constructor with many parameters, several optional, most of the same type. `new Pizza(true, false, true, false)` is unreadable and easy to get wrong in a way the compiler cannot catch.
Report report = Report.builder() .title("Q3 revenue") .groupBy(Region) .includeSubtotals() .build();**When it earns its keep.** Four or more parameters, or several optional ones, or combinations that need validating together. **When it does not.** Two or three required parameters — a plain constructor is shorter and clearer.
**Problem.** Exactly one instance must exist, and everything needs access to it.
The legitimate uses are narrow: genuinely stateless helpers, and objects representing a hardware or process-level resource that cannot meaningfully be duplicated. Even then, injecting the single instance costs nothing and keeps the dependency visible.
Sign in to keep a note here. It is free, and nobody else can see it.
Sign inWhat this chapter was for: