Card 02/ 08
Decorator Pattern Structure: The Class Diagram
A Decorator implements the Component interface and holds a Component, so it can wrap another decorator.
Decorator has four participants: the component interface, the concrete component that does the basic work, a decorator that implements the component and holds one, and the concrete decorators that each add one behaviour. This card reads each role off the Gang of Four's class diagram, and shows the one detail that makes stacking possible.
| Participant | Role |
|---|---|
| Component | The interface that both the plain object and every wrapper implement, here with operation(). |
| ConcreteComponent | The object that does the basic work, and the innermost object in any stack. |
| Decorator | Implements Component and holds a Component; by default it passes each call to the one it holds. |
| ConcreteDecorator | Adds one behaviour before or after passing the call on, such as logging or a retry. |
Read the two lines between Decorator and Component. The realisation arrow says a decorator is a component, so a client can use it wherever a component is expected. The aggregation says a decorator has a component, the hollow diamond at the decorator's end. Because the component it holds can be any component, it can be another decorator, which is how a stack forms: a decorator wrapping a decorator wrapping the concrete component.
The abstract Decorator class exists to hold the reference and pass calls on, so each concrete decorator overrides only the methods it changes. In a language that checks shape rather than inheritance, such as Python, a concrete decorator can implement the interface directly and skip the shared base class.
← → move through sections and cards