Composite pattern with two Examples

By | February 7, 2017

In this article I will discuss the Composite pattern with two C# code examples. One is the usual leaf node example and other being the binary tree structure example.

Become an Expert in Programming and Web Development.View all courses!

You can find about other design pattern in the series at the below link:

Design Patterns in C#

What is Composite Pattern ?

Composite pattern is another structural pattern which is used to handle the collection of objects which can be of same type. It makes the iteration and traversal of the object in the collection simple and convenient.

Client treats the parent and child or Node and leaf in same manner. This is a very simple and important pattern which we should be aware of. It has high usability and low complexity level.

Design Components in the Composite Pattern

Composite pattern is made of Component and Composite classes. The composite pattern has a collection of the component. The common functionalities of both of these classes are abstracted out in an interface.

In my implementation of the composite pattern I will consider the Leaf and Node class as same. If a node class does not have children I will consider it as the Leaf Node.

The first example I will discuss here is of simple parent- child scenario. In this scenario a single parent class can have many children class. Please have a look at the code below

In the above code I have single class which acts as component and composite. If the composite does not have any Nodes then it will be a Leaf.

Lets call this code from the client.

and the output of the above code is as following.

Composite pattern

Composite pattern

As we can see from the above code there is only single operation which is common for child as well as parent class. The method is Print(). Client only calls Parent method of the top most parent we get the desired result.

Binary Tree Example

As promised I will discuss this article with two examples of composite pattern. Other very good example of composite pattern is binary tree. A binary tree always have two children. In the binary tree which I have created, the parent is greater then the left child and less then the right child.

Lets create  the binary tree using composite pattern.

The above code is used to create a binary tree structure. These structures can be used for fast searching and iteration of child objects.

We can use composite pattern when:

  • We want client to treat the parent and child object in same way.
  • We have irregular structure of objects and composites of the objects.


In this article I have discussed composite pattern with C# example and given two very good examples of the scenarios where we can use this pattern.