Applied Design Patterns with Java
Structural :: Decorator (175) {C ch 12}
Collaborations
- Decorator forwards requests to its Component object. It may optionally perform additional operations
before and after forwarding the request.
Consequences
The Decorator pattern has the following consequences:
- More flexibility than static inheritance. The Decorator pattern provides a more flexible way to add responsibilities to
objects than with static inheritance. Responsibilities can be added and removed at run-time simply by attaching
and detaching them. In contrast, inheritance requires creating a new class for each additional responsibility.
This gives rise to many classes and increases the complexity of a system. Providing different Decorator
classes for a specific Component class allows mixing and matching responsibilities.
Decorators also make it easy to add a property twice. For example, to give a TextView a double border, simply attach
two BorderDecorators. Inheriting from a Border class twice is error-prone at best.
- Avoids feature-laden classes high up in the hierarchy.
Decorator offers a need-only basis to adding responsibilities. Instead of trying to support all
foreseeable features in a complex, customizable class, define a simple class and add functionality incrementally
with Decorator objects. Functionality can be composed from simple pieces. As a result, an application needn't pay for features it doesn't use. It's easy to define new kinds of Decorators independently from the classes
of objects they extend, even for unforeseen extensions. Extending
a complex class tends to expose details unrelated to the responsibilities added.
- A Decorator and its component aren't identical. A
Decorator
acts as a transparent enclosure. But from an object identity point of view, a decorated component is not identical
to the component itself. Don't rely on object identity when using decorators.
- Lots of little objects. A
design that uses Decorator often results in systems composed of many little objects that all look alike. The objects
differ only in the way they are interconnected, not in their class or in the value of their variables. Although
these systems are easy to customize by those who understand them, they can be hard to learn and debug.
Catalog Structural Prev Next