ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Key OOP Concepts Used with the Decorator Pattern | 133

simple inheritance. Depending on how the application’s written, even the compo-


nents would all have the same features. A pickup truck would be subclassed from the


same component as a luxury car—both inheriting features they don’t want and


wouldn’t use.


Wrapping Responsibilities


The Decorator design pattern is also known as the Wrapper pattern. The concept of


“wrapping” is at the heart of the Decorator design pattern. So what does it mean to


“wrap” one object in another? One way to think about wrapping is to imagine wrap-


ping a gift. The wrapper transforms the gift, but the gift does not inherit the character-


istics of the wrapper—it only uses the wrapping. Unlike subclassing, which extends


one class into another, wrapping allows one object to use another’s characteristics


without extending either the wrapped object or the object doing the wrapping.


The wrapping with which most ActionScript programmers are familiar is that used


for transforming data types from one type to another. For example, theNumberclass


can wrap a string variable, and then that variable has the characteristics of theNumber


class. Figure 4-3 illustrates a common wrapper function:


When we look at wrapping one object with another object, we can
think of it as a class intercepting API calls intended for a specific
instance of another class. The example in Figure 4-3 shows that the
Numberclass is intercepting a call to an instance of theStringclass. The
result is that thelvariable, an unsigned integer, is able to accept the
assignment of thesvariable as a number. That’s because thesvari-
able is wrapped in aNumber class and treated as a number.

Using the Decorator class, components are wrapped in decorators. The wrapping


class is a concrete instance of a decorator, and the wrapped class is an instance of the


concrete component class. Thus, the concrete component now “contains” the char-


Figure 4-3. Number class wrapping String class


Number class wraps string variable.

Now variable s has Number characteristics.
It acts like a number.
Free download pdf