- Chapter
- Chapter 1 — Design Pattern Fundamentals
- Prerequisites
- Topics 1.1–1.3; Volume I Chapter 5 (KISS, YAGNI)
- You will be able to
- Select patterns starting from problems and forces, evaluate their trade-offs against simpler alternatives, recognise when modern Java or a framework already solves the problem, and justify not using a pattern
- Covers
- Problem-first thinking · Trade-offs · When not to use
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally — Refactoring Toward (and Away From) Patterns
- 4A. Deep Dive — A Pattern Selection Worksheet
- 5. APIs / Features / Syntax — Built-in Alternatives to Classic Patterns
- 6. Practical Examples
- 7. Common Problems & Mistakes
- 8. Performance & Production Considerations
- 9. Architecture & Design Considerations
- 10. Interview Questions & Answers
1Concept / Definition
Pattern selection is the decision process of choosing whether — and which — pattern to apply to a design problem. It has three parts in the TOC:
| Part | Question |
|---|---|
| Problem-first thinking | What is the actual problem and which forces make it hard? |
| Trade-offs | Does the pattern's benefit outweigh its cost here, compared with simpler options? |
| When not to use | Is there no real force, or does the language/framework already solve it? |

2Why It Exists
After the GoF book, many developers learned patterns as solutions looking for problems ("pattern fever"): every object created by a factory, every class behind an interface, every behaviour a strategy. The result was over-engineered code. Joshua Kerievsky's Refactoring to Patterns (2004) proposed a better approach: evolve toward a pattern through refactoring when the code demands it — and sometimes refactor away from one. Problem-first selection is that discipline applied before writing code.
3Core Concepts
3.1 Problem-first thinking
Start with the symptom in the code or requirement, then identify the forces, then look for patterns whose intent matches.

| Step | Output | Example |
|---|---|---|
| State the problem | One sentence | "Adding a carrier requires editing the shipping calculator and 4 switches." |
| Identify forces | List | New carriers monthly; calculator must stay stable; carriers need separate tests |
| Find candidate patterns by intent | 2–3 patterns | Strategy, Template Method, plug-in via ServiceLoader |
| Compare consequences | Table | Strategy: + OCP, testable; − registry/selection needed |
| Choose simplest fit | Decision | Strategy beans in Map<String, ShippingRule> |
// Problem visible in code: repeated type switches (OCP violation)
Money cost(Shipment s) {
return switch (s.carrier()) {
case DHL -> dhlRate(s);
case UPS -> upsRate(s);
case FEDEX -> fedexRate(s); // added last month; next month: GLS
};
}
// Force: frequent additions along one axis → Strategy is justified3.2 Trade-offs
Every pattern resolves some forces and introduces costs.

| Pattern | Typical benefit | Typical cost |
|---|---|---|
| Strategy | Add variants without modifying context | More types; selection logic |
| Factory | Decouple creation from use | Indirection; another class |
| Builder | Readable construction of complex objects | Boilerplate; can hide invalid states if unchecked |
| Decorator | Add behaviour dynamically | Many small objects; identity/debugging complexity |
| Proxy | Transparent access control, laziness | Hidden behaviour; self-invocation pitfalls |
| Observer | Decoupled reactions | Hard-to-follow control flow; ordering issues |
| Abstract Factory | Consistent product families | Hard to add new product kinds |
Compare each candidate with the simplest alternative: a conditional, a lambda, a record, a framework feature. A pattern is justified when its benefit is needed now or its absence would be expensive to fix later.
3.3 When not to use

| Situation | Better choice |
|---|---|
| Only one variant exists and none is planned | Plain code (YAGNI) |
| The language provides it (lambda, enum, record, sealed type) | Use the language feature |
| The framework provides it (DI scope, AOP, events) | Use the framework mechanism |
| The problem is local and small | Simple conditional or method |
| The pattern's cost exceeds the problem's cost | Leave it |
| Team doesn't understand the pattern | Simpler design or training first |
// Strategy pattern ceremony for a two-line rule used in one place
interface DiscountStrategy { Money apply(Money total); }
class TenPercentDiscount implements DiscountStrategy { … }
class DiscountStrategyFactory { … }
// Simpler and just as clear
Money discounted = customer.isGold() ? total.times(0.9) : total;4How It Works Internally — Refactoring Toward (and Away From) Patterns
| Direction | Trigger | Example refactoring |
|---|---|---|
| Toward | Third variant, repeated switch, growing constructor | Replace Conditional with Strategy; Introduce Builder |
| Toward | External system leaks into domain | Introduce Adapter behind a port |
| Away | Strategy with one implementation for a year | Inline Strategy |
| Away | Factory returning new X() only | Replace Factory with Constructor |
| Away | Decorator chain nobody varies | Inline Decorator into implementation |
Refactoring toward patterns when forces appear keeps designs simple until complexity is earned; refactoring away removes patterns whose forces disappeared.
4ADeep Dive — A Pattern Selection Worksheet
4A.1 Worksheet
| Field | Content |
|---|---|
| Problem (1 sentence) | … |
| Forces (list) | variation? lifecycle? coupling? testability? performance? |
| Evidence | change history, roadmap, number of variants |
| Candidates | pattern A, pattern B, "no pattern" |
| Consequences table | benefit/cost for each candidate |
| Language/framework alternative | lambda? enum? Spring feature? |
| Decision + revisit trigger | "Strategy; revisit if selection rules become complex" |
4A.2 Worked example
Problem: "Several services must call three different SMS providers depending on country; providers change yearly."
| Candidate | Assessment |
|---|---|
| No pattern (if/else per country in each service) | Duplicated; providers leak into services ✘ |
Adapter per provider behind SmsPort | Isolates vendor APIs ✔ |
| + Strategy/registry keyed by country | Selection in one place ✔ |
| Abstract Factory | Only one product kind (SMS) — unnecessary ✘ |
| Decision | Adapter + registry; revisit if routing needs fallback rules (then Chain of Responsibility) |
5APIs / Features / Syntax — Built-in Alternatives to Classic Patterns
| Need | Java 25 / Spring feature | Replaces or simplifies |
|---|---|---|
| Interchangeable behaviour | Lambdas, method references | Strategy, Command classes |
| Closed set of types with operations | Sealed interfaces + pattern switch | Visitor |
| Immutable data with validation | Records | Hand-written value classes, some Builders |
| One shared instance | Spring singleton scope | GoF Singleton |
| Cross-cutting behaviour | Spring AOP, @Transactional, @Cacheable | Hand-written Proxies/Decorators |
| Creating configured objects | @Bean methods, ObjectProvider | Factories |
| Reacting to events | @EventListener | Hand-written Observer |
6Practical Examples
6.1 Selection decisions in one service
| Problem | Decision | Why |
|---|---|---|
| Vendor payment SDK in domain code | Adapter behind PaymentPort | Isolation, testability |
| Five discount rules, new ones quarterly | Strategy beans | Frequent variation |
| One tax rule per country, stable | Enum with behaviour | Closed small set |
| Order DTO with 4 fields | Record, no Builder | Few fields |
| Complex HTTP request configuration | JDK HttpRequest.newBuilder() | Library already provides Builder |
| Audit on every command | Event listener | Framework Observer |
6.2 Refactoring away a pattern
// Before: Abstract Factory for a single product family that never varied
interface ReportFactory { Header header(); Body body(); Footer footer(); }
class DefaultReportFactory implements ReportFactory { … }
// After: direct construction — the family never varied in three years
Report report = new Report(new Header(title), new Body(rows), new Footer(total));6.3 Anti-pattern: Golden Hammer
| Symptom | Example |
|---|---|
| Same pattern everywhere regardless of fit | "Every service gets a Facade, Factory and Strategy" |
| Pattern names in every class name | OrderProcessingStrategyFactoryImpl |
| Reviews rewarding pattern use | "Nice, you used Visitor" |
6.4 Communicating a pattern decision
ADR-031 — Shipping carriers as Strategy beans
Problem: every new carrier edits ShippingCalculator and 4 switches
(6 carriers in 9 months).
Forces: carriers added monthly; calculator must stay stable; carriers tested separately.
Options: (1) keep switches, (2) Strategy beans + registry,
(3) plug-in modules via ServiceLoader.
Decision: (2). Consequences: + OCP along carrier axis;
− selection by key must be validated at startup.
Revisit: if external partners must add carriers without our release → (3).7Common Problems & Mistakes
- Solution-first design ("let's use CQRS/Visitor here").
- Ignoring language features that make the pattern unnecessary.
- Not comparing with the simplest alternative.
- Keeping patterns after their forces disappear.
- Pattern names instead of domain names in code.
8Performance & Production Considerations
| Aspect | Consideration |
|---|---|
| Over-engineering | More objects, proxies and indirection — startup and debugging cost |
| Under-engineering | Duplicated logic and switches — regression risk in production |
| Pattern-specific | Some patterns affect runtime directly (Flyweight saves memory; Proxy may add latency) |
| Observability | Patterns at boundaries (adapters, proxies) are good instrumentation points |
Both over- and under-engineering have measurable runtime signatures, which is useful evidence when a pattern decision is revisited. Each Spring proxy, decorator and listener adds frames to stack traces and beans to the context, so dozens of speculative layers lengthen startup and slow down incident diagnosis; the Actuator startup endpoint and Java Flight Recorder show where that time goes. Event-based Observer implementations move failures out of the caller's path, so listeners need their own error handling and metrics, and a @TransactionalEventListener runs only after commit. Patterns chosen for runtime reasons should be verified with benchmarks: Flyweight for memory, caching proxies for latency, while object pools are rarely worth it on modern JVMs. Adapters at system boundaries are the natural place for timeouts, retries and per-vendor metrics, which makes them valuable even when only one vendor exists.
9Architecture & Design Considerations
- Selection discipline scales up: architecture patterns (microservices, event sourcing) need the same problem-first analysis — with far higher cost of error.
- Pattern guidance in engineering handbooks should include "when not to use".
- ADRs capture pattern decisions with forces and revisit triggers.
- Reviews should ask "what problem does this pattern solve here?".
10Interview Questions & Answers
What does problem-first pattern selection mean?
It means starting from the concrete problem in the code or requirement and the forces that make it hard, and only then looking for a pattern whose intent matches. I state the problem in one sentence, for example that adding a carrier requires editing the shipping calculator and four switches, then list the forces: carriers added monthly, a calculator that must stay stable, carriers tested separately. That points to Strategy, Template Method or plug-ins, which I compare with the simplest alternative, including no pattern at all. The opposite, solution-first design, picks a pattern because it is familiar or fashionable and then bends the problem to fit it, which produces over-engineered code.
When should you not use a design pattern?
When there is no force for it to resolve, or when something cheaper already resolves it. If only one variant exists and none is planned, a Strategy hierarchy is ceremony, and YAGNI says write the direct code. If the language solves the problem, use the language: a lambda instead of a Command class, an enum with behaviour instead of a small State hierarchy, a record instead of a Builder for four fields, a sealed interface with a pattern switch instead of Visitor. If Spring already provides it through DI scopes, AOP or events, use that. Also skip a pattern when its cost exceeds the problem, or when the team cannot maintain it.
How do lambdas affect pattern selection?
Lambdas remove most of the class boilerplate from behavioural patterns, which changes the cost side of the trade-off. A Strategy used to need an interface plus one class per variant; now it can be a functional interface such as Function or a custom ShippingRule, with variants written as lambdas or method references and held in a Map keyed by carrier. Command, Template Method callbacks, Observer listeners and simple factories, which become a Supplier, shrink in the same way. That makes patterns cheaper to apply, so the threshold for using one drops, but the forces still have to exist. Once a variant carries state or substantial logic, a named class is clearer than a long lambda.
What is the Golden Hammer anti-pattern?
Golden Hammer is the anti-pattern of applying a familiar pattern or technology to every problem regardless of fit, from the saying that if all you have is a hammer, everything looks like a nail. In code it shows up as every service getting a Facade, Factory and Strategy, class names like OrderProcessingStrategyFactoryImpl, and reviews that praise pattern use instead of asking what it solves. At architecture level it looks like Kafka for every integration or microservices for every team. The cause is usually comfort and a wish to appear sophisticated. The cure is problem-first selection, with no pattern as an explicit candidate and a named force behind every pattern used.
What does "refactoring toward patterns" mean?
It is Joshua Kerievsky's idea that patterns should be reached through refactoring when the code demonstrates the need, rather than designed in up front on speculation. You start with the simplest code, and when a force appears, such as a third variant, a repeated type switch or a constructor with too many parameters, you apply small behaviour-preserving steps like Replace Conditional with Strategy or Introduce Builder, guarded by tests. The same discipline runs in reverse: a Strategy that has had one implementation for a year is inlined, and a Factory that only returns new X() is replaced by a constructor. Complexity is earned by evidence and removed when it stops paying for itself.
How would you compare pattern candidates?
I make the comparison explicit and always include the simplest options. First I write down the forces: what varies, how often, lifecycle, coupling, testability and performance. Then I list two or three candidate patterns, plus no pattern and any language or framework feature that could do the job, such as a lambda, an enum or a Spring mechanism. For each I note concrete benefits and costs in this codebase: extra types, indirection, selection logic, debugging effort and how hard the choice would be to reverse. I pick the simplest option that resolves the forces that exist today, and record a revisit trigger for the forces I expect but cannot yet prove.
How do you document a pattern decision?
For a significant decision I use an ADR, and for a local one a short design note or a code comment linking to it. The record states the problem in one sentence, the forces, and the evidence behind them, such as six carriers added in nine months. It lists the options considered, always including no pattern, with the consequences of each, then the decision and its known costs, for example that strategy keys must be validated at startup. Most importantly it gives a revisit trigger, such as moving to ServiceLoader plug-ins if partners must add carriers without our release. Using domain names rather than pattern names in the code keeps the intent readable.
How does pattern selection discipline apply to architecture choices?
The discipline is identical, but the cost of a wrong choice is far higher, so it matters more. Architecture patterns such as microservices, event sourcing, CQRS or a service mesh each resolve specific forces: independent team deployment, a complete audit history, very different read and write loads, or uniform traffic policy across many services. I start from those forces and the evidence for them, compare against the simplest option, such as a modular monolith or CRUD with an audit table, and estimate the reversal cost, which for architecture is often months of work. Choices go into ADRs with revisit triggers, so the system grows into complexity instead of starting with it.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.