Which pattern, when
medium 45 minA pattern is an answer to one kind of pressure.
Chapter mnemonic
Three design-pattern families
Make the puppets. Fit the strings. Put on the show.
Which family covers fitting existing objects together?
Structural patterns. Creational patterns make objects and behavioral patterns coordinate them.
Video lesson · Chapter 1 of 6
Make a prediction
Which pattern, when (master matrix)
1:02Reel
Theory
Read or listen first. About 2 min.
What it is
A design pattern is a named answer to a problem that comes back in many programs, together with the situation it fits and the price it has. All four parts matter. A name without the situation is only a word.
The force is the pressure in your design that makes simple code hurt: a rule that changes every month, an object that behaves differently in each phase, a library with the wrong method names. You look for the force first. The pattern follows from it.
The matrix on this page is a lookup table with two sides. One side goes from force to pattern. The other side goes from a typical problem (elevator, parking lot, chess, cache, feed, logger) to its parts, its patterns and its data structures.
Why it exists
In a design round people often name patterns first and look for a place to put them afterwards. The result has more classes than the problem has facts. Starting from the force stops that, because no force means no pattern.
It also gives you the sentence that earns credit: force, then pattern, then cost. For example: prices change every month, so I make the price rule an object, and I pay with one more file per rule.
And it helps with the hardest question, which is when not to. If you know which pressure a pattern answers, you can say that the pressure is missing.
A short history
1977
Christopher Alexander and colleagues publish A Pattern Language: 253 patterns for towns, buildings and rooms, each with its problem and its solution.
1987
Kent Beck and Ward Cunningham bring the idea to programming in Using Pattern Languages for Object-Oriented Programs, a report for a workshop at OOPSLA 87.
1994
Gamma, Helm, Johnson and Vlissides publish Design Patterns, with 23 patterns in three groups: creational, structural and behavioural.
1996
Peter Norvig presents Design Patterns in Dynamic Languages and shows that many of the patterns shrink or disappear when the language already has the feature, for example functions as values.
Words to know
- Force
- The pressure that makes the simple version hurt.
- Creational
- Patterns about how objects come into being.
- Structural
- Patterns about how objects are put together.
- Behavioural
- Patterns about how objects share work and talk.
- Variation point
- The one place where the design is expected to differ.
- Keyword
- A word in the prompt that hints at a force. A hint, never a proof.
- Consequence
- What you gain and what you pay after using the pattern.
- Pattern soup
- A design with many patterns and no forces.
- Seam
- A clean place where a pattern could be added later.
How it works
Step through the idea, or press Play.
Find the force. What varies, or what must be kept apart?
Understand it
Start here
A key ring with one key per kind of lock
Asha looks after a school building. On the ring hang keys of different shapes. What matters is never how many keys there are. What matters is that Asha looks at the lock first.
The lock is the pressure, the key is the pattern, the handle is plain code.
Step 1
Ask what varies
Most useful patterns in a design round answer the question: what is likely to differ? Here is the short form. Learn this table before any other.
From force to pattern
| What varies or hurts | Cheap answer first | Pattern when that is not enough |
|---|---|---|
| A rule or algorithm, chosen from outside | A function parameter | Strategy |
| Behaviour, by the phase the object is in | An enum and a table of allowed moves | State |
| Who wants to know about a change | One direct call | Observer |
| Which class to create | A constructor, or a map from name to class | Factory |
| Extras around a call | A parameter or two | Decorator |
| A foreign interface with other names | One small function that translates | Adapter |
| An action that must be undone, queued or logged | A list of plain records | Command |
| Who handles a request, one after another | A loop over checks | Chain of responsibility |
| One thing or a group of things, treated alike | A list | Composite |
| A few steps inside a fixed order | A function with a callback | Template method |
Behaviour: which key?
Structure and creation: which key?
Step 2
Keywords are hints, not answers
Words in the prompt point at a force. They are useful for the first guess. But the same word can point at several forces, so a question must follow before you decide.
Words you hear, and the question to ask
| Pattern | Words that hint at it | Ask this before you decide |
|---|---|---|
| Strategy | multiple, different ways, algorithm, pricing, policy, calculation | Do the formulas differ, or only the numbers? |
| State | state, status, changes, transitions, lifecycle, idle, active | Does the same call behave differently in each phase? |
| Observer | notify, update, subscribe, listener, event, broadcast | Who must hear it, and does the list change? |
| Command | undo, redo, history, queue, execute, action | Must an action be kept after it ran? |
| Factory | create, type, different instances, product, generate | Is the class known only at run time? |
| Singleton | single, one, global, shared instance | Is it really one, or is one enough today? |
| Decorator | add, wrap, extend, enhance, additional | Can the extras be mixed in any order? |
| Chain of responsibility | handler, chain, pass, next, log, filter | Can one link stop the rest? |
different appears for Strategy and for Factory. update can mean Observer or a plain setter. This is why a keyword alone is not enough.Force first
- Prices change each month, so the rule is an object
- An order can be cancelled only before printing, so I need phases
- Both the screen and the mail want the news, so they subscribe
Name first
- I will use Strategy, Factory and Singleton here
- There is one shop, so it is a Singleton
- It says type, so there is a factory
Step 3
The master matrix
Six typical problems, filled in the same way. Read one row aloud and you have the first five minutes of an answer. The last column is the follow-up that decides whether the row fits your variant.
Master matrix: the parts
| Category and problem | Container: what holds | Item: what is managed | Manager: who decides |
|---|---|---|---|
| Hardware: elevator | Shaft, Floor | Car, Request | Dispatcher |
| Booking: parking lot | Floor, Spot | Vehicle, Ticket | ParkingSystem |
| Game: chess | Board, Square | Piece, Move | GameController |
| System: LRU cache | The cache itself | Entry (a node) | Cache |
| Social: feed | Timeline | Post | FeedService |
| Tools: logger | Registry of loggers | LogRecord | Logger |
Master matrix: the choices
| Problem | Patterns, and the force behind each | Structures and locks | Ask before using the row |
|---|---|---|---|
| Elevator | State: doors and motion limit the calls. Strategy: which car answers | Sorted set of stops per car, one lock or one worker thread per car | How many cars? One car needs no dispatcher rule |
| Parking lot | Strategy: the price. Factory only if vehicle kinds behave differently | Free spots per size in a heap or a bit set, map from ticket to spot, a lock around take | Which spot: nearest, or any? |
| Chess | Polymorphic pieces for moves, Command for undo. Flyweight only for pictures | 8 by 8 array, stack of moves. A blocking queue only for online matching | Do we need undo or online play? |
| LRU cache | Strategy if the eviction rule may change, Decorator for expiry or metrics | Hash map plus doubly linked list, one plain lock because a read also moves the entry | One thread or many? |
| Feed | Observer for new posts, Strategy for ranking | Merge of the newest posts of k people with a heap | Newest first, or ranked? |
| Logger | Chain or a list of handlers, Strategy for the format | Ring buffer or blocking queue to a writer thread, thread local context | May a record be lost when the buffer is full? |
How to read the columns
Container
What stores or holds the resources. Often a map or a grid inside.
Item
The resources being managed. They have an identity and a life.
Manager
The controller. It receives the request and keeps the rules.
Patterns
One per force, with the force written beside it.
Data structures
Chosen from the calls that must be fast, plus the lock that protects them.
Where the columns come from has its own pages: finding entities and owners for the first three, data structures for the last, and the problem analyzer for filling a new row in five minutes.
Worked example
A print shop, one force at a time
The shop takes print jobs. The prompt says: different customers pay differently, a job goes through steps, and people want to be told when it is ready. Three sentences, three possible forces. Let us ask about each.
Three questions, three decisions
You
You say customers pay differently. Is it the same formula with other numbers, or other formulas?
Interviewer
Other formulas. Schools pay a flat price per job, clubs pay per page. We invent a new one now and then.
You
Then the rule is a variation point. I make it a function that gets the job. A class per rule only if rules need their own data.
- Force: formulas change
- Pattern: Strategy, as functions
- Cost: one more name per rule
You
The steps: does the same request behave differently in each step?
Interviewer
No. Some moves are simply not allowed. You cannot cancel while it prints.
You
Then a table of allowed moves is enough. I keep State in reserve for the day a step gets its own behaviour.
You
Who is told when a job is ready?
Interviewer
The screen in the shop today, and mail next month.
You
Two listeners with one more coming, so the shop keeps a list of listeners. It does not know screen or mail.
Pattern soup: nine boxes, no forces
1/4One job
The shop prints jobs. A job has pages. So far one class would do.
usesimplements
The same shop with three answered forces
1/4The plain core
A shop that owns its jobs. The job guards its own moves with a table, so nobody can cancel while it prints.
owns (dies together)useshas (lives on)
Code
Write it in the order of the forces
Print shop with two patterns and one table
The moves are data. The job refuses every move that is not listed.
from dataclasses import dataclassMOVES = { ("new", "start"): "printing", ("new", "cancel"): "cancelled", ("printing", "finish"): "ready", ("ready", "collect"): "collected",}@dataclassclass Job: number: int pages: int cents: int status: str = "new" def fire(self, event): move = (self.status, event) if move not in MOVES: raise ValueError(f"cannot {event} a job that is {self.status}") self.status = MOVES[move]Lines 3 to 8
Four allowed moves, readable by anybody in the shop. A chain of ifs would hide the same four facts in code.
Why it is built this way
- A table beats the State pattern here because a phase has no behaviour of its own.
- If printing ever needs its own reaction to a call, the table grows into State classes.
Look-alikes
Same drawing, different intention
Several patterns have the same boxes and arrows. The picture does not tell them apart. The reason does. Three wrappers are the most common trap.
Three wrappers around a printer
1/4One contract
Everybody calls print. InkPrinter does it directly.
implementsuses
Pairs that are confused
| Pair | First | Second | Question that decides |
|---|---|---|---|
| Strategy and State | Chosen from outside, one job, stays | Moves on by itself, many calls | Who changes it? |
| Factory and Builder | Which class | Many parts, same class | Is the class open, or the parts? |
| Factory method and Abstract factory | One product | A family that must match | How many products belong together? |
| Decorator and Chain | All run, each adds | Any link may stop it | May a link end the call? |
| Observer and Mediator | One tells many | Many talk through one | Is there a star or a web? |
| Facade and Adapter | Makes many calls simple | Makes one interface fit | Simplify or translate? |
| Strategy and Template method | Whole algorithm, by composition | Some steps, by inheritance | Swap at run time? |
| Command and Memento | Keeps the action | Keeps the state | Is undo easy to compute? |
All of them
The 23 classic patterns by force
Creation and structure
| Pattern | Force in one line | Not when |
|---|---|---|
| Factory method | The class is known only at run time | There is one class |
| Abstract factory | Parts of one family must not be mixed | Parts are independent |
| Builder | Many optional parts, checked at the end | Three parameters, or named arguments |
| Prototype | Copying a prepared object is easier than making it | Copies share hidden state |
| Singleton | A second instance would be wrong in this process | One is only enough for now |
| Adapter | Useful class, wrong interface | You can change the class |
| Bridge | Two things vary independently | Only one varies |
| Composite | Trees of parts treated like one part | The list is flat |
| Decorator | Extras in any mix | The set of extras is fixed |
| Facade | Callers need one simple door | It hides one method |
| Flyweight | Huge numbers of objects share data | There are 32 of them |
| Proxy | Control when or whether the real thing is reached | Nothing to control |
Behaviour
| Pattern | Force in one line | Not when |
|---|---|---|
| Chain of responsibility | One of several handlers takes it, in order | The handler is known |
| Command | An action must outlive its call | Nobody undoes, queues or logs it |
| Interpreter | A small language with rules to run | A library or a table can do it |
| Iterator | Walk without showing the inside | The language gives it to you |
| Mediator | Many objects talk to many | Two objects talk |
| Memento | Save and restore without opening the object | The inverse action is easy |
| Observer | An open list wants to hear changes | One fixed receiver |
| State | The same call differs by phase | Only a few moves are forbidden |
| Strategy | An algorithm is chosen from outside | Only a number differs |
| Template method | Fixed order, some open steps | Steps are chosen at run time |
| Visitor | New operations on a closed set of classes | New classes are frequent |
Combining
Two locks on one door
Real problems mix a few patterns. The safe way is one pattern per force, each in its own class, so that each can be removed alone. Here is how the print shop's two patterns meet in one call.
One call, two patterns, one table
The life of a job
Taking a key out
Removing a pattern is also design
If the force is gone, or never came, the pattern should go. Interviewers like this question, because it shows whether you know the reason and not only the recipe. Two removals that are always worth knowing follow.
From a global object to one that is passed in
The till reads the tax from a global object. Nothing in its constructor says so.
class Settings: _one = None def __init__(self, tax_percent): self.tax_percent = tax_percent @classmethod def get(cls): if cls._one is None: cls._one = cls(20) return cls._oneclass HiddenTill: def total(self, cents): return cents + cents * Settings.get().tax_percent // 100Line 2
One field for the whole process. Two tests that want two taxes now share it and depend on their order.
Grading
How good is your pattern choice?
The prompt says: the machine sells drinks, accepts coins, and gives change. Which pattern do you name?
BreaksSingleton, Factory, Observer and Strategy
- How
- Four names in the first minute.
- Limit
- No force for any of them. Each will be questioned, and the time is gone.
- Choose when
- Never.
WorksState, because it is a vending machine
- How
- Remembered from a list of problems.
- Limit
- Right name, but no reason, so the follow-up is hard to answer.
- Choose when
- As a first guess that you test with a question.
StrongState, because the same button means something else in each phase
- How
- The candidate lists the calls and shows that select does different things before and after a coin, then compares with a table.
- Limit
- More classes than a table. Say so.
- Choose when
- When phases have behaviour. See the vending machine.
The sentence in four parts
- 1
Force
Price formulas change, and the shop picks one per customer.
- 2
Pattern
So a price rule is an object behind one method.
- 3
Cost
I pay with one more name per rule and one more jump for the reader.
- 4
Exit
If it stays one formula with other numbers, I remove it and keep a table.
Summary
The whole topic in one minute.
Ask what varies. If nothing varies, write the plain version. If something varies, name the force, try the cheaper answer first (a value, a function, a table), and use the pattern when the cheaper answer stops being enough.
Keywords in the prompt are hints. different can mean Strategy, Factory or only a number. The answer to a follow-up question decides.
Say it in one breath: force, pattern, cost, and what would make you remove it.
- Read the lock, then pick the key: force first, pattern second.
- Try a value, a function or a table before a pattern.
- Keywords hint. A question decides.
- One pattern per force, each in its own class.
- The same drawing can be three patterns. The intention is the name.
- One example object is not a reason for Singleton.
- Say the cost and the exit.
Sources
- Norvig: Design Patterns in Dynamic Languages
- Beck and Cunningham: Using Pattern Languages for Object-Oriented Programs (1987)
- Design Patterns (book, 1994)
- A Pattern Language (book, 1977)
- Java: Comparator
- Java: FilterInputStream
- Jakarta Servlet: FilterChain
- Qt: undo framework
- Spring: JdbcTemplate
- SQLite: the OS interface (VFS)
- Java: Integer
- Java: Runtime