Design Patterns

Sefism.

Chapter 08

Choosing a pattern

Map the problem in front of you to a pattern, and recognise the patterns already inside the frameworks you use.

Problem to pattern map

Also called which design pattern to use

What
A quick lookup from symptom to candidate pattern. Confirm the fit before applying it.
Why
Most real uses of patterns start from a recognisable symptom, not from the catalogue.
Code
too many constructor args     -> Builder
type chosen by config          -> Factory Method
third-party API does not fit   -> Adapter
extras in any combination      -> Decorator
if-else picking an algorithm   -> Strategy
switch on a status everywhere  -> State
many listeners for one event   -> Observer
undo, queue or replay actions  -> Command (+ Memento)
tree of parts and wholes       -> Composite

Patterns you already use

Also called patterns in the wild

What
Express and Koa middleware is Chain of Responsibility, DOM events are Observer, Java I/O streams are Decorators, Spring beans default to singletons, and React context is a form of dependency injection.
Why
Recognising them helps you learn a framework faster and extend it the intended way.

Patterns and first-class functions

Also called functional patterns, lambda

What
In languages with first-class functions, Strategy, Command and Template Method often shrink to passing a function, and Iterator becomes a generator.
Why
Reach for the lightest form: a function parameter is usually clearer than a one-method interface and three classes.

Telling similar patterns apart

Also called decorator vs proxy, strategy vs state, adapter vs facade

What
Adapter changes an interface; Facade simplifies a subsystem. Decorator adds behaviour; Proxy controls access. Strategy is picked by the caller; State switches itself.
Why
These pairs share a structure, so intent is what distinguishes them in design discussions.

Refactoring towards a pattern

Also called emergent design

What
Start with simple code and introduce a pattern when duplication or a growing conditional shows the need, in small tested steps.
Why
Patterns added in response to real pressure fit the problem; patterns added up front fit a guess.
08 · Choosing a pattern8 / 9