The Composite Pattern is a pattern that’s designed to use smaller objects to build up larger ones, and those larger objects could themselves actually just be smaller parts of even larger objects, and so on.

The real-world examples that Olsen provides in Design Patterns in Ruby and the Gang of Four mention in Design Patterns: Elements of Reusable Object-Oriented Software (I picked up a second book) are for Graphics application and Graphical User Interfaces where a programmer might want to group together objects to form larger components. For example different shapes were all part of the Shape group, and various line styles were all Lines… but then they were all part of the DrawnObjects group.

Digging down into the Composite Pattern reveals three important parts, and the best way to visualize it is as a tree branching down. At the top is the Component, and the next step down the tree would be the other two options, the Leaf or the Composite. UML time!

The Component is the parent that all of the other leaves and branches are a part of. In the GUI example it would be the DrawnObjects.

Next up could be a Leaf, which Olsen describes best when he says the Leaf represents the “simple, indivisible building block of the process” (114). In the GUI example I started a Leaf could be a dot. It’s not really a line and not really a shape (well, let’s pretend it’s not technically a part of both) and a dot can’t be broken down any further.

And finally is the pattern’s namesake object, the Composite. The composite derives from the Component, but is a component itself in that it’s made up of more Leaves that all implement a similar action. The composite is also responsible for keeping track of (and adding and deleting) it’s leaves. In the GUI example Shapes and Lines would both be Composites.

The key to the composite is that it stands on it’s own as a leaf and a component. A Shape is definitely a leaf of a drawn object, and definitely a component of Circles, Squares and Triangles.

Honestly, I haven’t been able to come up with a solid real world example for this pattern yet, but I just started digging around the Limelight source code to see if I could spot it in there. In the meantime, I recommend checking out Olsen’s cake baking example, which just makes me too hungry to explain here.