Design Patterns Java™ Workbook

(Michael S) #1

Chapter 27. Decorator.................................................................................................................................


Chapter 27. Decorator


Ordinarily, an object inherits behaviors from its superclasses. As earlier chapters have shown,
you can apply the STATE and the STRATEGY patterns to alter the behavior of an object
dynamically. Like STATE and STRATEGY, the DECORATOR pattern relies on polymorphism,
but DECORATOR combines polymorphism with delegation to let you extend an object's
behavior. The intent of DECORATOR 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 DECORATOR 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 DECORATOR.


The DECORATOR 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 COMPOSITE pattern, whose purpose is to compose aggregate objects,
the purpose of DECORATOR is to compose behavior.


Structurally, DECORATOR 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.

Free download pdf