The role of the Decorator pattern is to provide a way of attaching new state and
behavior to an object dynamically. The object does not know it is being "decorated,"
which makes this a useful pattern for evolving systems. A key implementation
point in the Decorator pattern is that decorators both inherit the original class
and contain an instantiation of it.
As its name suggests, the Decorator pattern takes an existing object and adds to it. As
an example, consider a photo that is displayed on a screen. There are many ways to
add to the photo, such as putting a border around it or specifying tags related to the
The beauty of this pattern is that:
• The original object is unaware of any decorations.
• There is no one big feature-laden class with all the options in it.
• The decorations are independent of each other.
• The decorations can be composed together in a mix-and-match fashion.
Now, we can specify the players in the Decorator pattern in a UML diagram, shown
in Figure 2-2. Because this is the first pattern we are describing in UML, we'll take it
slowly. (The UML that we need for patterns in this book is covered in Chapter 1 and
summarized in Table 1-1.) The essential players in this UML diagram are:
An original class of objects that can have operations added or modified (there
may be more than one such class)
An operation inIComponent objects that can be replaced (there may be several
The interface that identifies the classes of objects that can be decorated
(Component is one of these)
A class that conforms to theIComponent interface and adds state and/or behavior
(there may be more than one such class)
The center of the UML diagram is theDecorator class. It includes two types of relationships
with theIComponent interface:
The is-a relationshipis shown by a dotted arrow from theDecorator to
IComponent, indicating that Decorator realizes the IComponent interface. The fact
thatDecorator inherits from IComponent means that Decorator objects can be
used whereverIComponent objects are expected. The Component class is also in an
is-a relationshipwithIComponent, and therefore the client can use Component and
Decoratorobjects interchangeably—the heart of the Decorator pattern.
The has-a relationshipis shown by an open diamond on theDecorator, linked to
IComponent. This indicates that the Decorator instantiates one or more
IComponentobjects and that decorated objects can outlive the originals. The
Decoratoruses the component attribute (of type IComponent) to invoke any
replacementOperation it might wish to override. This is the way the Decorator
pattern achieves its objective.
TheaddedBehavior operation and the addedState attribute in the Decorator class are
other optional ways of extending what is in the originalComponent objects. We'll look
at some examples momentarily.
Excelta - Conseils et services informatiques
MCSD For Microsoft .Net
MVP Windows Systems Server / Biztalk Server
Certifié ITIL et Microsoft Biztalk Server