5.4 Composite

The problem is that you may have a set of Primitive objects which you also group into Composite objects, and you want to be able to treat the primitive and the composite objects the same. You also want to be able to have composites made of mixtures of composites and primitives, and so on.

The solution is to have a base class called, say Component, with both the Primitive and Composite classes inheriting from it. Composite has a member, typically an array, which holds any number of Component objects.

When you use a Composite pattern the Component class usually has some virtual method doSomething() that you override in the child classes. Typically the primitive children of Component override doSomething() in various particular kinds of ways and the Composite child class overrides doSomething() to (a) walk through a loop to call doSomething for all of _pchildren[i] and (b) possibly do some additional step peculiar to the particular Composite class.

Figure 5.5. The Command pattern


It's sometimes useful to think of a Composite pattern in terms of a tree. The Primitive objects are the leaves of the tree, and the Composite objects are the forks. When you call the doSomething at some fork, you end up working your way out to all the leaves above this fork. Thus, in Figure 5.6, if we supposed that *pA points to the object in the small circle, then the call pA->doSomething() will cascade down to all of the other objects included in the large oval.

Figure 5.6. A Composite pattern tree


In the Pop Framework we use the Composite pattern with our graphical sprite objects. That is, we have a base class cSprite with a some 'primitive' sprite child classes: cSpriteBubble, cSpriteIcon, and cPolygon. We also have a cSprite child class called cSpriteComposite, and this class has a CArray _pspritechild of cSprite * objects.

Java uses the Composite pattern for its graphics classes: there is a base Component class which has as child classes (a) Primitive classes such as Button and Scrollbar, and (b) a Composite class called Container, which holds an array of Component objects. In addition, the Container class has (c) child classes Panel, Window, Frame, Dialog, etc.

    Part I: Software Engineering and Computer Games
    Part II: Software Engineering and Computer Games Reference