Card 04/ 05

ExerciseDifficulty: Advanced2 min

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.

  1. An HTTP client is given a retry policy object, which decides how long to wait before each new attempt.
  2. A document is a draft, then in review, then published; its publish method does something different in each, and moves the document to the next stage.
  3. A report base class fixes the steps load, format and send, and each kind of report supplies only format.
  4. Each edit in a text editor is an object with do and undo, kept in an undo history.
  5. A stock price feed calls every chart and alert that registered with it whenever the price changes.
  6. Users in a chat send their messages to a room object, which decides who receives each one.
  7. A support ticket goes to the help desk, then a specialist, then an engineer, and stops at the first who can solve it.
  8. A file stream is wrapped in buffering and then in encryption, and every write goes through both to the file.
Show the answers
The pattern for each description, and the question that decided it
DescriptionPatternThe deciding question
Retry policy StrategyWho decides? The caller, by passing the policy in
Document stages StateWho decides? The document, moving itself to the next stage
Report steps Template MethodWho decides? A subclass, filling in one step
Undo history CommandWhen does it run? Now, and it is kept to be undone later
Price feed ObserverWho reacts? Every subscriber, each for itself
Chat room MediatorWho reacts? One object decides for all
Support ticket Chain of ResponsibilityDoes every object pass it on? No; it stops at the first that solves it
File stream DecoratorDoes 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.