Part 3 of 7 · 1 min read
Problem to pattern
A decision table.
When a requirement appears, ask what is varying or what is hard. Then look in this table.
| The problem you see | Pattern | Module |
|---|---|---|
| One class must choose a concrete class by a code or setting | Simple factory or Factory Method | L3-1 |
| Several objects that must match each other, in variants | Abstract Factory | L3-2 |
| An object with many optional parts, to be built safely | Builder | L3-3 |
| Exactly one shared instance (be careful) | Singleton, or better, injection | L3-4, L3-6 |
| New objects that are copies of a ready model | Prototype | L3-5 |
| A class should receive, not create, its helpers | Dependency injection | L3-6 |
| The same job done in several swappable ways | Strategy | 1 |
| One change must reach many listeners that you do not know | Observer | 2 |
| Behaviour that depends on the object's stage of life | State | 3 |
| Requests that must be queued, logged, repeated or undone | Command | 4 |
| Features that combine freely and are added at run time | Decorator | 5 |
| A class with the wrong interface for your code | Adapter | 6 |
| Many services behind one simple entry point | Facade | 6 |
| Same steps in a fixed order, a few steps differ | Template Method | 7 |
| Several handlers, unknown which one will take a request | Chain of Responsibility | 8 |
| A tree of parts and groups treated alike | Composite | 9 |
| Visit elements of a collection without exposing it | Iterator | 9 |
The table is a start. Always check the consequences, and ask whether a plain method or a lambda would do.
Check yourself: 1. Which pattern fits "the fee rule can be hourly or flat"? 2. Which fits "the booking moves from requested to confirmed to checked in"? 3. Which fits "wrap a vendor's SMS class so our code sees one interface"?