Decorator Pattern
Add behavior to one object by wrapping it in another object with the same interface, so features stack at run time instead of multiplying subclasses.
Overview
The problem it solves A class needs optional extras: compression, encryption, logging, a cache. With subclasses, every combination is a new class, and the combinations grow fast. A decorator is an object that implements the same interface as the thing it wraps, adds one behavior, and passes everything else through. You pick the extras when you build the object, in any order, and the caller cannot tell a wrapped object from a plain one.
The pattern is a structural pattern from the Gang of Four book (Gamma, Helm, Johnson and Vlissides, *Design Patterns*, 1994). The book's roles are Component (the shared interface), ConcreteComponent (the plain object), Decorator (a base that holds a component and forwards to it) and ConcreteDecorator (one extra behavior).
The arithmetic is why the pattern exists. With subclasses, you need one class for every combination of features, including the plain object, which is 2 to the power of the number of features. With decorators, you need one class per feature. Three optional features mean 2 × 2 × 2 = 8 subclasses against 3 decorator classes. Four features mean 16 subclasses against 4 decorators. Ten features mean 2^10 = 1,024 subclasses against just 10 decorators.
The class diagram shows how the four roles fit together, using the store from the example below.
Interview questions
- What are the parts of the Decorator pattern, and why does the decorator base class exist?
- Show the smell that Decorator removes, and the fix.
- How does Decorator differ from inheritance, and when is inheritance still the better choice?
- What goes wrong with deep decorator stacks?
- When would you choose Decorator over Strategy?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio