ActionScript 3.0 Design Patterns

(Chris Devlin) #1

134 | Chapter 4: Decorator Pattern


acteristics of the wrapper, but the characteristics are not inherited. Figure 4-4 shows


an example.


The concrete component that’s wrapped by another class borrows characteristics of


the wrapping class. When those characteristics are not needed, the instance of the


concrete class is simply instantiated without being wrapped.


Flexibility and Adaptability


One good OOP practice is to create your classes so that they can be extended but not


changed. If a class is changed, especially one with subclasses, you can quickly


destroy an application. So the trick is to set up your classes so that it’s easy to extend


them, yet keep them safe from alteration.


The Decorator design pattern allows you to do this. The model is grounded in a sin-


gle class that is the superclass to all others. This core class is an abstract component


class. An abstract decorator class is subclassed from this class, re-implementing the


core methods. (In the context of ActionScript 3.0, theabstractnature of the class is


simulated by using theoverridestatement when re-implementing methods in sub-


classes.) All the other concrete component and decorator classes have the same root


superclass, even though the decorator classes are subclassed from the abstract deco-


rator class, and the component classes are directly from the abstract component


class. So, when the concrete component objects are wrapped in concrete decorator


objects, both objects share the same root superclass. Thus, the decorated objects can


keep the core object unmodified while changing its responsibilities.


In a larger OOP framework, the Decorator pattern can add and subtract


functionality from an object by wrapping selected components with selected


decorators. Second, it can add more than a single functionality to an object by wrap-


ping one wrapper inside another wrapper. As a result, the design pattern can change


functionality without changing structure.


Figure 4-4. Concrete decorator wrapping concrete component


Concrete component wrapped in
concrete decorator.
Free download pdf