Card 02/ 08

ConceptDifficulty: Intermediate1 min

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.

Decorator participants
Each participant and its role
ParticipantRole
ComponentThe interface that both the plain object and every wrapper implement, here with operation().
ConcreteComponentThe object that does the basic work, and the innermost object in any stack.
DecoratorImplements Component and holds a Component; by default it passes each call to the one it holds.
ConcreteDecoratorAdds 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.