Card 04/ 05
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.
- 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.
- 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.
- A
Moneyvalue holds an amount and a currency, both required, with no variants. - 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.
- A data import framework reads files, and each application that uses it subclasses the importer to supply its own parser.
- A process must hold exactly one connection to a hardware device, because a second connection makes the device reset.
Show the answers
| Problem | Choice | The deciding clue |
|---|---|---|
| Light and dark widgets | Abstract Factory | Several products must match, and mixing families is the bug |
| Customer test records | Prototype | A costly set-up shared by objects that differ in two fields |
| Money | Constructor | Two required fields, one class, nothing varies |
| Email message | Builder | Many optional parts, and a rule checked once at the end |
| Import framework | Factory Method | The framework calls a method each subclass overrides to create its parser |
| Device connection | Singleton | A 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.
← → move through sections and cards