Java Reference
In-Depth Information
The Decorator pattern works by allowing layers to be added to and removed from a base object. Each layer can
provide behavior (methods) and state (variables) to augment the base object. The layers can be chained and freely
associated with this pattern, allowing you to create advanced object behavior from a set of fairly simple building
blocks.
The Decorator pattern is naturally suited for applications involving overlays and views that can be dynamically
built. Groupware products, which allow networked teams to combine edit work on a single base document, are
one example. Some image editors are well-suited to the Decorator, as well as most applications involving text,
paragraph or document formatting. At a lower level, the Decorator allows functionality to be built up as a
combination of filters applied to a base model. Stream-based I/O or communication endpoints (sockets) offer a
few examples, like the BufferedReader , which allows you to read line by line from a Reader object.
The Decorator pattern can be compared to the various optional extras available for an automobile. Working with a base model, the
factory can add additional features such as rust-proofing, cruise control, upgraded sound systems, remote entry, and so on. With each
“layer” added to the vehicle, the vehicle acquires new characteristics, and the price increases accordingly. (Of course, unlike the
Decorator pattern, customers cannot change these features once they drive the vehicle off the lot.)
Implementation
The Decorator class diagram is shown in Figure 3.6 .
Figure 3.6. Decorator class diagram
For the Decorator pattern, implement the following:
Component - Represents the component containing generic behavior. It can be an abstract class or an interface.
Decorator - Decorator defines the standard behaviors expected of all Decorators. Decorator can be
an abstract class or an interface. The Decorator provides support for containment; that is, it holds a reference to a
Component , which can be a ConcreteComponent or another Decorator . By defining the Decorator class
hierarchy as a subclass of the component(s) they extend, the same reference can be used for either purpose.
One or more ConcreteDecorators - Each Decorator subclass needs to support chaining (reference to a
component, plus the ability to add and remove that reference). Beyond the base requirement, each Decorator can
define additional methods and/or variables to extend the component.
Benefits and Drawbacks
The Decorator offers the opportunity to easily adjust and augment the behavior of an object during runtime. In
addition, coding can become substantially easier, since you need to write a series of classes, each targeted at a
specific bit of functionality, rather than coding all behavior into the component itself. This also tends to make the
component more easily extensible in the future, since changes can be introduced by coding new classes.
 
 
Search WWH ::




Custom Search