Part 4 of 7 · 1 min read
Look-alikes
Same shape, different aim.
Many patterns have the same shape in code. A context holds an interface, and implementations vary. What differs is the intent. Ask who chooses, what changes and why.
| Pair | Same shape | The difference |
|---|---|---|
| Strategy and State | A context delegates to an interface | The client picks a strategy. A state changes by itself as events happen |
| Strategy and Command | An object holding one action | A strategy is an algorithm the context calls. A command is a request with its receiver and arguments, run later |
| Decorator and Adapter | A wrapper around one object | A decorator keeps the interface and adds behaviour. An adapter changes the interface |
| Decorator and Chain of Responsibility | Objects in a line | A decorator always forwards. A handler may stop the request |
| Decorator and Composite | Objects holding objects | A decorator wraps one object. A composite holds many |
| Facade and Adapter | A new front class | A facade simplifies many classes. An adapter makes one class fit |
| Factory Method and Template Method | A subclass fills in a step | In Factory Method the step creates an object. In Template Method it is any step of an algorithm |
| Observer and Chain | One request reaches several objects | Observer tells all of them. A chain stops at the first that handles it (usually) |
When two patterns seem to fit, state the intent in a sentence. The one whose sentence matches your problem is the right one.
Check yourself: 1. How do you tell Strategy from State in a vending machine? 2. A class that logs every call to another class: decorator or adapter?