Card 07/ 08

ExerciseDifficulty: Intermediate2 min

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.

  1. A report generator must produce the same report as PDF, HTML or plain text, chosen in a settings file.
  2. A new payment provider's library has makePayment(cents), and your code calls charge(amount).
  3. A game must create enemies whose class depends on the current level, without the level code naming each class.
  4. When a stock price changes, three charts and an alert service must update.
  5. A folder contains files and other folders, and you need the total size of everything inside.
  6. An HTTP request passes through authentication, logging and rate limiting before it reaches the handler.
  7. A configuration object takes fourteen settings, most of them optional.
  8. An editor must let users undo their last twenty actions.
Show the families
Each problem, its family, and the clue that decides it
ProblemFamilyThe clue
Report as PDF, HTML or text BehaviouralThe output format is an interchangeable algorithm chosen at run time, which is Strategy.
makePayment against charge StructuralTwo interfaces that do not fit. Adapter makes one look like the other.
Enemies chosen by level CreationalThe problem is which class gets created. Factory Method fits.
Charts react to a price BehaviouralMany objects must hear about one change, which is Observer.
Files inside folders StructuralSingle items and groups must be treated alike. Composite fits.
Request through several checks BehaviouralEach handler does its part and passes the request on: Chain of Responsibility.
Fourteen settings CreationalPutting a complex object together is a creation problem. Builder fits, or keyword arguments in Python.
Undo twenty actions BehaviouralEach 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.