Part 5 of 6 · 2 min read
Costs
When to avoid it.
Costs and choices
GoF lists two benefits. Decorators are more flexible than static inheritance, because behaviour can be added and removed at run time and the same extra can be added twice. And they avoid feature-heavy classes high up in a hierarchy. A plain class is extended step by step, so an application does not pay for features it does not use.
GoF also lists two liabilities. A decorator and its component are not identical, so code must not rely on object identity. And a design with decorators has many small objects that look alike and differ only in how they are connected, which is easy to customize for those who understand it but can be hard to learn and debug.
Two more points help in design rounds.
- Keep the component interface small. A decorator must forward every method, so a large interface means a lot of boring forwarding code.
- A decorator that must know the exact type of what it wraps is a sign that the design is wrong.
Decorator and Strategy both change the behaviour of an object by composition. A decorator wraps an object from outside, keeps its interface and can be stacked. A strategy is plugged into a context from inside and replaces one step. Decorator and Composite (module 9) are also close: a decorator wraps exactly one object, while a composite holds many.
Common mistake
Using a decorator when a simple field would do. A "discount" decorator on a booking with one fixed discount adds classes for no gain.
Interview angle
Answer in your head first, then open it.
What is the Decorator pattern?
An object is wrapped in another with the same interface, and the wrapper adds behaviour before or after forwarding the call.
Why not subclass?
Each combination of features needs a new class, and subclassing is fixed at compile time.
Examples?
Java I/O streams, coffee or pizza toppings, logging or caching wrappers around a service.
Check yourself: 1. Name one benefit and one liability from GoF. 2. How does a decorator differ from a strategy?
Words you will meet
| Word | Meaning |
|---|---|
| Decorator | A wrapper with the same interface that adds behaviour |
| Component | The interface shared by the wrapper and the wrapped object |
| Wrapper | Another word for a decorator |
| Cross-cutting concern | Behaviour many classes need, such as logging |
| Forwarding | Passing a call on to the wrapped object |