Decorator
Adds behaviour to an object by wrapping it in another object with the same interface, without changing the original class.
Why it matters
You want to add extras like logging, caching or retries to some objects, in different combinations, without writing a subclass for every combination.
The idea
Instead of a subclass for every combination (LoggedCachedRetryingClient and so on), you stack small wrappers: a retry wrapper around a cache wrapper around the real client. Each wrapper adds one feature and passes the call along.
Wrapping a present in layers: paper, then ribbon, then a card. It's still the same present underneath, and you can add or skip any layer.
Gift layers don't affect each other. Code wrappers do, so the order matters: caching outside retries behaves differently from retries outside caching.
How it works
- Start with an object that implements an interface: read().
- Write a wrapper class that implements the same interface and holds another object of that interface.
- In its read(), do the extra work (write a log line, check a cache), then call the inner object's read().
- Wrap again for more features: Logging(Caching(Real())).
- Callers can't tell they're talking to a wrapper; they just call read().
Example
Java's file streams (a BufferedInputStream around a FileInputStream), and Python's @decorators for logging or timing functions.
Key points
- Same interface as the wrapped object, so wrappers can stack.
- Avoids an explosion of subclasses for every feature combination.
- Follows open/closed: add features without editing classes.
- Python's @ syntax is a related idea for functions.
Common mistakes
- Wrappers that change what the method means, rather than just adding to it.
- Wrapping in the wrong order (for example, caching errors).
Not true: The order in which decorators are stacked never changes the result.
In fact: Order matters: with the cache in the wrong place, a failure is stored and served again and again. Choose the order on purpose.
In the interview
Decorator wraps an object with another that has the same interface and adds one behaviour, like logging, caching or retries. Wrappers can be stacked in any combination, which avoids an explosion of subclasses.
Part of Unit 6: Design patterns in the free System Design course.