234 | Chapter 6: Composite Pattern
the DisplayObject class. The more commonly used Sprite class extends
DisplayObjectContainer, and is the preferred base class for composite objects.
The obvious question then is whether we can leverage the child handling methods in
theDisplayObjectContainerclass without having to re-implement them. We can
indeed, and will develop a composite airplane to show how in some cases, it’s better
to use the built-in child-handling methods.
Creating a Composite Airplane
Figure 6-8 shows the composite airplane that will be developed in this example. We
will leverage thedisplay listto build the visual components. The utility of the com-
posite pattern will be demonstrated by automatically calculating the weight of the
total aircraft, by adding up component weights. In addition, the composite pattern
implementation will help keep track of damage to each component, and figure out
the overall damage to the aircraft. You will also see how particular components can
be removed from the structure when damage exceeds a certain amount using the
built-in methods of theDisplayObjectContainer class.
Developing the Component and Composite Classes for the Airplane
Because we will use the built-in methods of theDisplayObjectContainerclass to
manipulate child objects, the component and composite classes are simple to imple-
ment. We need only to define theoperationsfor the composite structure. The first
step is to define an interface for the operations supported by the airplane.
Figure 6-8. Twin-engine composite airplane (top-down view)