Java Reference
In-Depth Information
Chapter 27. Decorator
Ordinarily, an object inherits behaviors from its superclasses. As earlier chapters have shown,
you can apply the S
TATE
and the S
TRATEGY
patterns to alter the behavior of an object
dynamically. Like S
TATE
and S
TRATEGY
, the D
ECORATOR
pattern relies on polymorphism,
but D
ECORATOR
combines polymorphism with delegation to let you
extend
an object's
behavior. The intent of D
ECORATOR
is to let you compose an object's behavior dynamically.
A Classic Example of Decorator: Streams
The Java class libraries provide a classic example of the D
ECORATOR
pattern in the overall
design of Java input and output streams. A
stream
is a serial collection of bytes or characters,
such as those that appear in a document. In Java, each stream object usually contains another
stream object to which it forwards its operations. This structure is typical of D
ECORATOR
.
The D
ECORATOR
pattern arranges for each decorator object to contain another decorator
object. In this regard, a decorator is like a slim composite whose elements each have a single
child. Unlike the C
OMPOSITE
pattern, whose purpose is to compose aggregate objects,
the purpose of D
ECORATOR
is to compose
behavior.
Structurally, D
ECORATOR
arranges classes in a hierarchy and distributes operations across
this hierarchy. Each class in the hierarchy typically has a constructor that requires another
instance of a class in the hierarchy. For example, Figure 27.1 shows a portion of
the
OutputStream
hierarchy from the Java class libraries.