Design Patterns in Ruby: Composite

A clear example of the Composite pattern

The intent

According to the GoF, the intent of the Composite pattern is to:

“Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.”

The example

The Composite pattern provides a powerful and flexible way of handling part-whole object hierarchies. By ignoring the difference between individual objects and compositions of objects, client usage is simplified. Within the Composite pattern, individual objects are referred to as leafs, and composite objects are referred to as composites. Generally, both leafs and composites are referred to as components. The Composite pattern generates a tree structure.

The example below is annotated so as to be self-descriptive. To understand the Composite pattern, study the example.

Some Tidbits

Explicit parent references

It is often prudent to give a child within a composite structure a reference to its parent. With a parent reference, it becomes very easy to traverse up the composite structure.

Leave it to the leaf

A leaf type class is responsible for defining operations of the primitive objects in the composite tree.

Decorate the request

Often times, composites forward received requests to their leafs. In such a case, a composite might perform additional operations before and/or after the incoming request is handled. It could be said in such a case that the composite has decorated the request to the leaf.

Ordering children

In some composite designs, it is necessary to maintain a strict ordering of child components. When child ordering is an issue, you must design child access and management interfaces carefully to properly manage the sequence of children.

Overly general?

Though powerful, flexible and elastic, the Composite pattern may be too general for certain system designs. Sometimes, you may want a given type of composite to contain only certain types of components. However, the Composite pattern does not have any built-in constraints with which to enforce such requirements.

Going deeper

The Composite pattern is one of many valuable design patterns. To learn more, check out the seminal work on Design Patterns: The GOF Design Pattern book.