AlgoViz

Which pattern, when

medium 45 min

A 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

0:00 / 4:38

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

  1. 1977

    Christopher Alexander and colleagues publish A Pattern Language: 253 patterns for towns, buildings and rooms, each with its problem and its solution.

  2. 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.

  3. 1994

    Gamma, Helm, Johnson and Vlissides publish Design Patterns, with 23 patterns in three groups: creational, structural and behavioural.

  4. 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.

Step 1 of 4

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.

Asha, the ring and the doors

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 hurtsCheap answer firstPattern when that is not enough
A rule or algorithm, chosen from outsideA function parameterStrategy
Behaviour, by the phase the object is inAn enum and a table of allowed movesState
Who wants to know about a changeOne direct callObserver
Which class to createA constructor, or a map from name to classFactory
Extras around a callA parameter or twoDecorator
A foreign interface with other namesOne small function that translatesAdapter
An action that must be undone, queued or loggedA list of plain recordsCommand
Who handles a request, one after anotherA loop over checksChain of responsibility
One thing or a group of things, treated alikeA listComposite
A few steps inside a fixed orderA function with a callbackTemplate method
The middle column is not a weaker version. Very often it is the better design.

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

PatternWords that hint at itAsk this before you decide
Strategymultiple, different ways, algorithm, pricing, policy, calculationDo the formulas differ, or only the numbers?
Statestate, status, changes, transitions, lifecycle, idle, activeDoes the same call behave differently in each phase?
Observernotify, update, subscribe, listener, event, broadcastWho must hear it, and does the list change?
Commandundo, redo, history, queue, execute, actionMust an action be kept after it ran?
Factorycreate, type, different instances, product, generateIs the class known only at run time?
Singletonsingle, one, global, shared instanceIs it really one, or is one enough today?
Decoratoradd, wrap, extend, enhance, additionalCan the extras be mixed in any order?
Chain of responsibilityhandler, chain, pass, next, log, filterCan 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 problemContainer: what holdsItem: what is managedManager: who decides
Hardware: elevatorShaft, FloorCar, RequestDispatcher
Booking: parking lotFloor, SpotVehicle, TicketParkingSystem
Game: chessBoard, SquarePiece, MoveGameController
System: LRU cacheThe cache itselfEntry (a node)Cache
Social: feedTimelinePostFeedService
Tools: loggerRegistry of loggersLogRecordLogger

Master matrix: the choices

ProblemPatterns, and the force behind eachStructures and locksAsk before using the row
ElevatorState: doors and motion limit the calls. Strategy: which car answersSorted set of stops per car, one lock or one worker thread per carHow many cars? One car needs no dispatcher rule
Parking lotStrategy: the price. Factory only if vehicle kinds behave differentlyFree spots per size in a heap or a bit set, map from ticket to spot, a lock around takeWhich spot: nearest, or any?
ChessPolymorphic pieces for moves, Command for undo. Flyweight only for pictures8 by 8 array, stack of moves. A blocking queue only for online matchingDo we need undo or online play?
LRU cacheStrategy if the eviction rule may change, Decorator for expiry or metricsHash map plus doubly linked list, one plain lock because a read also moves the entryOne thread or many?
FeedObserver for new posts, Strategy for rankingMerge of the newest posts of k people with a heapNewest first, or ranked?
LoggerChain or a list of handlers, Strategy for the formatRing buffer or blocking queue to a writer thread, thread local contextMay a record be lost when the buffer is full?
Seven columns in two tables: category, problem, container, item, manager, patterns, structures. Containers and items are covered in finding entities, structures on their own page.

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

  1. You

    You say customers pay differently. Is it the same formula with other numbers, or other formulas?

  2. Interviewer

    Other formulas. Schools pay a flat price per job, clubs pay per page. We invent a new one now and then.

  3. 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
  4. You

    The steps: does the same request behave differently in each step?

  5. Interviewer

    No. Some moves are simply not allowed. You cannot cancel while it prints.

  6. You

    Then a table of allowed moves is enough. I keep State in reserve for the day a step gets its own behaviour.

  7. You

    Who is told when a job is ready?

  8. Interviewer

    The screen in the shop today, and mail next month.

  9. 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

PrintShop- instance: PrintShop+ getInstance()Job- pages: int

1/4One job

The shop prints jobs. A job has pages. So far one class would do.

usesimplements

Every red box must be read, tested and explained. The interviewer will ask why for each of them.

The same shop with three answered forces

ownsPrintShop- jobs: Map<int, Job>+ place(customer, pages)+ fire(number, event)+ onChange(listener)Job- number: int- status: Status+ fire(event)

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)

Five boxes. Each one can be defended with a sentence that the interviewer said.

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.

1 of 4

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

«interface»Printer+ print(doc)InkPrinter+ print(doc)

1/4One contract

Everybody calls print. InkPrinter does it directly.

implementsuses

Ask for the intention: translate, add, or control. The answer is the name.

Pairs that are confused

PairFirstSecondQuestion that decides
Strategy and StateChosen from outside, one job, staysMoves on by itself, many callsWho changes it?
Factory and BuilderWhich classMany parts, same classIs the class open, or the parts?
Factory method and Abstract factoryOne productA family that must matchHow many products belong together?
Decorator and ChainAll run, each addsAny link may stop itMay a link end the call?
Observer and MediatorOne tells manyMany talk through oneIs there a star or a web?
Facade and AdapterMakes many calls simpleMakes one interface fitSimplify or translate?
Strategy and Template methodWhole algorithm, by compositionSome steps, by inheritanceSwap at run time?
Command and MementoKeeps the actionKeeps the stateIs undo easy to compute?

All of them

The 23 classic patterns by force

Creation and structure

PatternForce in one lineNot when
Factory methodThe class is known only at run timeThere is one class
Abstract factoryParts of one family must not be mixedParts are independent
BuilderMany optional parts, checked at the endThree parameters, or named arguments
PrototypeCopying a prepared object is easier than making itCopies share hidden state
SingletonA second instance would be wrong in this processOne is only enough for now
AdapterUseful class, wrong interfaceYou can change the class
BridgeTwo things vary independentlyOnly one varies
CompositeTrees of parts treated like one partThe list is flat
DecoratorExtras in any mixThe set of extras is fixed
FacadeCallers need one simple doorIt hides one method
FlyweightHuge numbers of objects share dataThere are 32 of them
ProxyControl when or whether the real thing is reachedNothing to control

Behaviour

PatternForce in one lineNot when
Chain of responsibilityOne of several handlers takes it, in orderThe handler is known
CommandAn action must outlive its callNobody undoes, queues or logs it
InterpreterA small language with rules to runA library or a table can do it
IteratorWalk without showing the insideThe language gives it to you
MediatorMany objects talk to manyTwo objects talk
MementoSave and restore without opening the objectThe inverse action is easy
ObserverAn open list wants to hear changesOne fixed receiver
StateThe same call differs by phaseOnly a few moves are forbidden
StrategyAn algorithm is chosen from outsideOnly a number differs
Template methodFixed order, some open stepsSteps are chosen at run time
VisitorNew operations on a closed set of classesNew classes are frequent
Twelve plus eleven is twenty three. You do not need all of them. You need the column in the middle.

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

Rule, table and listeners never talk to each other. Only the shop knows all three.

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

Line 2

One field for the whole process. Two tests that want two taxes now share it and depend on their order.

1 of 3

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. 1

    Force

    Price formulas change, and the shop picks one per customer.

  2. 2

    Pattern

    So a price rule is an object behind one method.

  3. 3

    Cost

    I pay with one more name per rule and one more jump for the reader.

  4. 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