Decorator
11 Mar 2022Intent
Attach additional responsibility to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Also known as
Wrapper
Applicability
Use decorator:
- to add responsibilities to individual objects dynamically and transparently, i.e. without affecting other objects.
- for responsibilities that can be withdrawn.
- when extension by subclassing is impractical.
Structure
Participants
- Component: defines the interface for objects that can have responsibilities added to them dynamically.
- Concrete Component: defines an object to which additional responsibilities can bt attached.
- Decorator: maintains a reference to a Component object and defines an interface that conforms to Component's interface.
- Concrete Decorator: adds responsibility to the component.
Collaborations
Decorator forwards requests to it's Component object. It may optionally perform additional operations before and after forwarding the request.
Consequences
The decorator pattern:
- has more flexibility then static inheritance.
- avoids feature laden classes high up in the hierarchy.
- A decorator and it's components aren't identical.
- A design that uses decorator often results in syste,s composed of lots of little objects that all look alike.
Sample Code
Related Patterns
- Adapter: a decorator is different from am adapter in that a decorator only changes an object's responsibilities, not it's interface; an adapter will give an object a completely new interface.
- Composite: A decorator can be viewed as a degenerate composite with only one component. However, a decorator adds additional responsibilities - it isn't intended for object aggregation.
- Strategy: A decorator lets you change the skin of an object; a strategy lets you change the guts. These are two alternative way of changing an object.