Skip to content
David Cumps
Design Patterns - Composite Pattern

Design Patterns - Composite Pattern

Originally published on my old blog at cumps.be on July 27, 2008.

It’s been a little while again. I blame myself for installing World of Warcraft again, too addictive. Anyway, time for the Composite Pattern. This is one I find hard to describe clearly.

Let’s start with the definition: “Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.”

The easiest way to understand this pattern is the notion of the tree structure in the definition. If you can make a tree in code, you can apply this pattern :)

An additional requirement has popped up for our game yesterday. We used to only have TacticalMoves, but now it’s needed to have those defined in a more granular way, where one move might consist of several submoves.

First of all, we define a new class, called TacticalComponent, which will serve as a base class for our TacticalMove and the new type we’ll introduce.

Composite Pattern Component

As you can see, this class consists mainly of two parts: the properties to hold some game-specific information, and additional methods to deal with the new feature request of having submoves, which are nothing more than children.

This TacticalComponent is an abstract class, where each method and property throws an exception, and only defines them as virtual instead of abstract. By doing this, we give the subclasses the choice which methods and properties they are going to override.

Composite Pattern Class Diagram

In our case both classes implement Description and Name, but only TacticalPlan implements the parent-child logic.

The nice part is that you have already encountered this pattern, for example when working in Windows Forms, where every control is a Control, and painting a form paints the form and all its child controls, without you having to walk the tree. Likewise in our TacticalPlan, the Print method displays itself along with all its children.

Print

Having introduced these two new classes, we can now rewrite our WorldOrders class to only accept one TacticalComponent, and treat it as a whole.

Rewritten WorldOrders class

The test code to illustrate this now composes the tree as follows:

Test Code

Resulting in the following orders:

Testing Composite Pattern

I’ve uploaded the solution again. This was one of the more difficult patterns to explain so far, so don’t be too hard on me :)

Some additional information on the Composite Pattern:

You May Also Like