Card 04/ 05

ExerciseDifficulty: Advanced2 min

Practice: Choosing How Each Object Gets Created

Six short problems, from a themed widget kit to a plain value object.

Choosing a creational pattern is a matter of asking what varies when the object is created, and this exercise gives six problems to practise on. For each, name the pattern, or name the constructor, and give the clue in the problem that decided it.

  1. A desktop toolkit draws buttons, menus and scroll bars, and an application must use either the light set or the dark set throughout, never a mix.
  2. A test suite needs hundreds of customer records that differ only in an id and a name, and the base record takes a second to load from fixtures.
  3. A Money value holds an amount and a currency, both required, with no variants.
  4. An email message has a recipient, and optionally a subject, a body, attachments, copies and a reply-to address, and it must not be sent without a recipient.
  5. A data import framework reads files, and each application that uses it subclasses the importer to supply its own parser.
  6. A process must hold exactly one connection to a hardware device, because a second connection makes the device reset.
Show the answers
The pattern for each problem, and the clue
ProblemChoiceThe deciding clue
Light and dark widgets Abstract FactorySeveral products must match, and mixing families is the bug
Customer test records PrototypeA costly set-up shared by objects that differ in two fields
Money ConstructorTwo required fields, one class, nothing varies
Email message BuilderMany optional parts, and a rule checked once at the end
Import framework Factory MethodThe framework calls a method each subclass overrides to create its parser
Device connection SingletonA second instance would be a fault and not only a waste

Problem 6 has a second good answer: create the one connection at start-up and pass it to the code that uses it, which keeps the single instance and avoids the global access point. Problem 2 could also be a builder with defaults, but the one-second load is the clue that copying a loaded record is the cheaper way to make the rest.