Card 07/ 08
Practice: Sorting Problems Into Pattern Families
Eight one-line problems; is each about creating, composing or communicating?
Sorting a problem into creational, structural or behavioural is the first step in finding a pattern for it, and it is a skill practised on problems rather than on pattern names. Below are eight design problems. For each one, decide which family it belongs to by asking what the problem is about: making an object, fitting objects together, or dividing work between them.
- A report generator must produce the same report as PDF, HTML or plain text, chosen in a settings file.
- A new payment provider's library has
makePayment(cents), and your code callscharge(amount). - A game must create enemies whose class depends on the current level, without the level code naming each class.
- When a stock price changes, three charts and an alert service must update.
- A folder contains files and other folders, and you need the total size of everything inside.
- An HTTP request passes through authentication, logging and rate limiting before it reaches the handler.
- A configuration object takes fourteen settings, most of them optional.
- An editor must let users undo their last twenty actions.
Show the families
| Problem | Family | The clue |
|---|---|---|
| Report as PDF, HTML or text | Behavioural | The output format is an interchangeable algorithm chosen at run time, which is Strategy. |
makePayment against charge
| Structural | Two interfaces that do not fit. Adapter makes one look like the other. |
| Enemies chosen by level | Creational | The problem is which class gets created. Factory Method fits. |
| Charts react to a price | Behavioural | Many objects must hear about one change, which is Observer. |
| Files inside folders | Structural | Single items and groups must be treated alike. Composite fits. |
| Request through several checks | Behavioural | Each handler does its part and passes the request on: Chain of Responsibility. |
| Fourteen settings | Creational | Putting a complex object together is a creation problem. Builder fits, or keyword arguments in Python. |
| Undo twenty actions | Behavioural | Each action becomes an object that can be reversed, which is Command. |
Problem 2 is the one most often placed in the wrong family, because the adapter changes what a call does. The problem it solves is a mismatch of shapes between two existing pieces, and that makes it structural. Problem 6 can look structural for the same reason, since the handlers form a line. What decides it is that each handler chooses whether to act, which is a division of work.
← → move through sections and cards