ActionScript 3.0 Design Patterns

(Chris Devlin) #1

132 | Chapter 4: Decorator Pattern


more like the nesting dolls from Japan and Russia. The innermost doll is the compo-


nent, and it’s placed into a decorator. Then the component and decorator are placed


into another decorator, and then into the next decorator. Figure 4-2 shows this


model.


Probably the most important thing to remember about the Decorator pattern is that


its purpose is to allow additional elements to be added to a class without altering the


base class. So instead of making changes by changing the class, the class is decorated


with subclasses that don’t interfere with the class from which the decorators were


derived.


Key OOP Concepts Used with the Decorator Pattern


Sometimes when you think about key OOP concepts such asinheritance, you have to


consider its larger consequences. The upside of inheritance is that once a superclass


has been established, all the subclasses inherit its features. However, you may not


want or need all the “stuff” for every subclass from a superclass. If you want to add


functionality to an object, subclassing may not be the way to go, because everything


else subclassed from the same superclass may be unnecessarily burdened by unused


functionality.


Unwanted Inheritance


At the end of this chapter, you will see an example of a car dealership where users


select models of cars with a choice of options for those cars. If all the options were


derived from a superclass, that would mean that every car would have all the


options, whether or not you wanted them. One option in the example is a rear view


camera used with minivans and large SUVs with limited rear vision. Such an option


would be superfluous on a sports car such as a Chevrolet Corvette, Morgan, or Fer-


rari. However, with subclassing, that’s exactly what would happen. Every subclass


gets everything from the superclass. So here’s a case where we’d have to look beyond


Figure 4-2. Component wrapped in series of decorators


#3
Concrete decorator
#3

#2
Concrete decorator
#2

#1
Concrete decorator
#1

Concrete component
Free download pdf