According to popular books on design patterns, there are 23 design patterns. Some of the simple ones include singleton, factory, prototype, interface, proxy etc. There are other patterns that are not quite so simple. Sometimes, we do not use them correctly. In the coming weeks, I will blog on a few such design patterns. The first in the series is the composite pattern.

An example of composite pattern is building complex shapes. Circle, triangle, rectangle, polygon, line, arc are simple shapes. Complex shapes are built as a collection of simple shapes.

I want to explain composite pattern by taking an example. An organization is a collection of people. An organization can contain other organizations. A simple class diagram of an organization from the perspective of an email system is shown below:


In the above class diagram, a common base class – Alias has a Name property. The Person class has an Email property. The Organization class has a DistributionGroup property. The Organization class also has a List of Alias objects.

Alias is the base class of out which all classes are composed. Organization is the composite class which contains a collection property. Organization itself is derived from the base class so that the collection can hold other Organization objects.

Most composite systems follow the above design pattern. In the previous example, Shape is the base class. Circle, Triangle etc are derived from the Shape class and represent components. A CompositeShape class is derived from the Shape class and holds a list of Shapes – Circles, Triangles, and other CompositeShapes.

Composite design pattern

Leave a Reply

Your email address will not be published. Required fields are marked *