ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 5 · Software Design & Design Patterns
  4. Volume III
  5. Pattern Selection
Book 5 · Volume III — Creational & Structural Design Patterns · Topic 1.4

Pattern Selection

Problem-first thinking, trade-offs and when not to use a pattern

9 min readStage 2 · Frameworks & design8 interview questions
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. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — Refactoring Toward (and Away From) Patterns
  5. 4A. Deep Dive — A Pattern Selection Worksheet
  6. 5. APIs / Features / Syntax — Built-in Alternatives to Classic Patterns
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 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:

PartQuestion
Problem-first thinkingWhat is the actual problem and which forces make it hard?
Trade-offsDoes the pattern's benefit outweigh its cost here, compared with simpler options?
When not to useIs there no real force, or does the language/framework already solve it?
Table 1 — Three parts of selection
Problem-first pattern selection
Figure 1 — Problem-first pattern selection

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.

Which kind of pattern might help?
Figure 2 — Which kind of pattern might help?
StepOutputExample
State the problemOne sentence"Adding a carrier requires editing the shipping calculator and 4 switches."
Identify forcesListNew carriers monthly; calculator must stay stable; carriers need separate tests
Find candidate patterns by intent2–3 patternsStrategy, Template Method, plug-in via ServiceLoader
Compare consequencesTableStrategy: + OCP, testable; − registry/selection needed
Choose simplest fitDecisionStrategy beans in Map<String, ShippingRule>
Table 2 — Problem-first steps
JAVA
// 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 justified

3.2 Trade-offs

Every pattern resolves some forces and introduces costs.

Modern Java often replaces pattern boilerplate
Figure 3 — Modern Java often replaces pattern boilerplate
PatternTypical benefitTypical cost
StrategyAdd variants without modifying contextMore types; selection logic
FactoryDecouple creation from useIndirection; another class
BuilderReadable construction of complex objectsBoilerplate; can hide invalid states if unchecked
DecoratorAdd behaviour dynamicallyMany small objects; identity/debugging complexity
ProxyTransparent access control, lazinessHidden behaviour; self-invocation pitfalls
ObserverDecoupled reactionsHard-to-follow control flow; ordering issues
Abstract FactoryConsistent product familiesHard to add new product kinds
Table 3 — Benefit vs cost

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

When not to use a pattern
Figure 4 — When not to use a pattern
SituationBetter choice
Only one variant exists and none is plannedPlain 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 smallSimple conditional or method
The pattern's cost exceeds the problem's costLeave it
Team doesn't understand the patternSimpler design or training first
Table 4 — Reasons not to apply a pattern
JAVA
// 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

DirectionTriggerExample refactoring
TowardThird variant, repeated switch, growing constructorReplace Conditional with Strategy; Introduce Builder
TowardExternal system leaks into domainIntroduce Adapter behind a port
AwayStrategy with one implementation for a yearInline Strategy
AwayFactory returning new X() onlyReplace Factory with Constructor
AwayDecorator chain nobody variesInline Decorator into implementation
Table 5 — Evolving designs (Kerievsky)

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

FieldContent
Problem (1 sentence)…
Forces (list)variation? lifecycle? coupling? testability? performance?
Evidencechange history, roadmap, number of variants
Candidatespattern A, pattern B, "no pattern"
Consequences tablebenefit/cost for each candidate
Language/framework alternativelambda? enum? Spring feature?
Decision + revisit trigger"Strategy; revisit if selection rules become complex"
Table 6 — Selection worksheet (usable in ADRs)

4A.2 Worked example

Problem: "Several services must call three different SMS providers depending on country; providers change yearly."

CandidateAssessment
No pattern (if/else per country in each service)Duplicated; providers leak into services ✘
Adapter per provider behind SmsPortIsolates vendor APIs ✔
+ Strategy/registry keyed by countrySelection in one place ✔
Abstract FactoryOnly one product kind (SMS) — unnecessary ✘
DecisionAdapter + registry; revisit if routing needs fallback rules (then Chain of Responsibility)
Table 7 — Worked selection

5APIs / Features / Syntax — Built-in Alternatives to Classic Patterns

NeedJava 25 / Spring featureReplaces or simplifies
Interchangeable behaviourLambdas, method referencesStrategy, Command classes
Closed set of types with operationsSealed interfaces + pattern switchVisitor
Immutable data with validationRecordsHand-written value classes, some Builders
One shared instanceSpring singleton scopeGoF Singleton
Cross-cutting behaviourSpring AOP, @Transactional, @CacheableHand-written Proxies/Decorators
Creating configured objects@Bean methods, ObjectProviderFactories
Reacting to events@EventListenerHand-written Observer
Table 8 — Language and framework alternatives

6Practical Examples

6.1 Selection decisions in one service

ProblemDecisionWhy
Vendor payment SDK in domain codeAdapter behind PaymentPortIsolation, testability
Five discount rules, new ones quarterlyStrategy beansFrequent variation
One tax rule per country, stableEnum with behaviourClosed small set
Order DTO with 4 fieldsRecord, no BuilderFew fields
Complex HTTP request configurationJDK HttpRequest.newBuilder()Library already provides Builder
Audit on every commandEvent listenerFramework Observer
Table 9 — Decisions with reasons

6.2 Refactoring away a pattern

JAVA
// 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

SymptomExample
Same pattern everywhere regardless of fit"Every service gets a Facade, Factory and Strategy"
Pattern names in every class nameOrderProcessingStrategyFactoryImpl
Reviews rewarding pattern use"Nice, you used Visitor"
Table 10 — Golden Hammer

6.4 Communicating a pattern decision

TEXT
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

AspectConsideration
Over-engineeringMore objects, proxies and indirection — startup and debugging cost
Under-engineeringDuplicated logic and switches — regression risk in production
Pattern-specificSome patterns affect runtime directly (Flyweight saves memory; Proxy may add latency)
ObservabilityPatterns at boundaries (adapters, proxies) are good instrumentation points
Table 11 — Operational view

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

Q1L1 · BasicConcept

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.

Q2L1 · BasicTricky

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.

Q3L2 · IntermediateCode

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.

Q4L2 · IntermediateConcept

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.

Q5L3 · Senior EngineerConcept

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.

Q6L3 · Senior EngineerTrade-off

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.

Q7L4 · Technical ArchitectDesign

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.

Q8L5 · Solution ArchitectDesign

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.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.