GoF Design Patterns – Composite Design Pattern


The Composite design pattern is a structural pattern that allows us to work with individual objects and a group of objects in the same way. It allows us to hide details of working with a single or a collection of objects behind the same interface. This pattern represents a tree-like structure where the nodes represent individual objects, and the entire tree represents a group of objects. The Composite pattern is useful when we have a group of objects that should be treated as a single object.

Probably the most simple use case to get a feeling of what this pattern does is to see how it can be applied to model directory structure:

In the above case, the composite design pattern allows us to execute the same operation on a group of elements or on a single element in the same way. For example, the getSize method can be executed on a file in the same way as it can be executed on a directory. The only difference is that when it is executed on a directory, it will also execute the getSize method on each child element recursively.

In the structure section, components of this pattern are described. In the above example, the file would take the role of a leaf, and the directory would take the role of a composite. Both would implement the same interface that would represent the file system element.

More on this pattern…

To read more on this and the other patterns, get “GoF Design Patterns Distilled” book from Amazon or Leanpub: