140 | Chapter 4: Decorator Pattern
Figure 4-5 shows what you should see in your Output window when you test the
movie.
To understand what’s going on in the Decorator pattern, go back and look at
Figure 4-2. The example application first instantiated aConcreteComponent( )object.
That object displays a message pointing to its decorations. Imagine that object
(testComponent) as the smallest can to the far left in Figure 4-2. That can is then
placed into decorator Can #1. At this point, the concrete component object
(testComponent) is decorated with Can #1, but retains its original properties –much
in the same way that a lawn decorated with a family of gnomes still retains its prop-
erty of green grass. Next, Can #1, which now contains the concrete component, is
dropped into Can #2. Now Can #2 has both Can #1 and the Concrete component
Can. Thus, Can #2 has all of the properties of itself plus those of the cans inside.
In a sense, the whole process works like the compound operator, plus-equal (+=).
Each decorator attaches itself to the existing component and its decorator. As each
decorator is added, all the previous ones are retained but not duplicated, unless you
add the same decorator more than once. So, as the output shows, you can add as
many decorations as you want simply by wrapping them in the existing object in one
of the decorators.
Example 4-6. DecTest.as
package
{
import flash.display.Sprite;
public class DecTest extends Sprite
{
public function DecTest( )
{
//Instantiate Concrete Component
var testComponent:Component = new ConcreteComponent( );
//Wrap first decorator around component
testComponent=new DecConA(testComponent);
//Wrap second decorator around component
testComponent=new DecConB(testComponent);
//Output results
trace(testComponent.getInformation( ));
}
}
}
Figure 4-5. Decorations on component