176 | Chapter 4: Decorator Pattern
Because more than one decorator can be selected, as each selected option is located,
the concrete object can be wrapped more than once. Thus, any or all of the options
can be added to the selected auto.
Summary
The Decorator design pattern excels in adding features to core objects without hav-
ing to fundamentally change those objects. Like the ornaments on a Christmas tree,
the ornaments change the appearance of the tree, but the tree itself is not changed at
all. Anything from the appearance of a web site to the contents of an online shop-
ping cart can be structured using a Decorator pattern.
The Decorator should be considered a core design pattern when your project has to
be updated with the addition of new objects and new features for those objects. We
like to think of the Decorator as a “100-year” pattern. Imagining concrete compo-
nents as types of people and decorations as the clothes they wear, it’s not too diffi-
cult to envision a web site being updated with different kinds of people spanning a
century—from a blacksmith at the beginning of the 20th century to a nanotechnolo-
gist at the beginning of the 21st century. Likewise, all kinds of people can be styled
with a range of clothing over the same time span, from a blacksmith’s leather apron
in 1900 to an astronaut’s spacesuit in 2000. However, the programmer who is think-
ing ahead from one century to the next is able to use a Decorator pattern, and
doesn’t have to change the core component at all. He just adds more concrete com-
ponents and decorators as needed.
At the same time that the Decorator pattern is open to adding new features without
changing the structure of the program, both components and decorators can be
deleted when they’re no longer needed. Further, changes to existing components and
decorators are easy to make without altering anything other than their specifics, such
as a string’s label or a number’s value.
The Decorator pattern, though, has certain drawbacks. For example, in this chapter,
some readers may have been thinking that they could have programmed the same
exact functionality for some of the sample applications using a fraction of the code
and far fewer classes. That’s definitely true, and for specific applications, the Decora-
tor design pattern may be like swatting a fly with an elephant gun. However, like all
design patterns, the developer has to be judicious in selecting which, if any pattern,
he wants to employ. That decision needs to be made not just on the current size of
the application, though. When starting any project where the Decorator pattern is
considered, you have to ask yourself: are the concrete components and decorators
going to grow and change or are they going to be fairly static? So, even though your
application may begin as an acorn, you have to envision the oak tree as a possibility
and plan accordingly.