Card 04/ 05
Practice: Naming the Behavioural Pattern From Its Intent
Eight short descriptions, from a retry policy to an undo history.
Naming a behavioural pattern from a description comes down to asking who decides, when it runs, and how many objects take part, and this exercise gives eight descriptions to practise on. For each, name the pattern and the question that decided it.
- An HTTP client is given a retry policy object, which decides how long to wait before each new attempt.
- A document is a draft, then in review, then published; its
publishmethod does something different in each, and moves the document to the next stage. - A report base class fixes the steps load, format and send, and each kind of report supplies only
format. - Each edit in a text editor is an object with
doandundo, kept in an undo history. - A stock price feed calls every chart and alert that registered with it whenever the price changes.
- Users in a chat send their messages to a room object, which decides who receives each one.
- A support ticket goes to the help desk, then a specialist, then an engineer, and stops at the first who can solve it.
- A file stream is wrapped in buffering and then in encryption, and every write goes through both to the file.
Show the answers
| Description | Pattern | The deciding question |
|---|---|---|
| Retry policy | Strategy | Who decides? The caller, by passing the policy in |
| Document stages | State | Who decides? The document, moving itself to the next stage |
| Report steps | Template Method | Who decides? A subclass, filling in one step |
| Undo history | Command | When does it run? Now, and it is kept to be undone later |
| Price feed | Observer | Who reacts? Every subscriber, each for itself |
| Chat room | Mediator | Who reacts? One object decides for all |
| Support ticket | Chain of Responsibility | Does every object pass it on? No; it stops at the first that solves it |
| File stream | Decorator | Does every object pass it on? Yes; each adds a layer |
Descriptions 1 and 2 are the pair most often swapped, because both hold an object that does the varying work. The retry policy is chosen from outside and never replaces itself; the document's stage replaces itself as the document moves on. Descriptions 6 and 5 differ in the same way as their patterns: the room decides who receives a message, while the feed leaves each listener to decide what a price means to it.
← → move through sections and cards