An Absolute Beginner’s Tutorial for Understanding and Implementing Composite Pattern in C#

The aim of this article is to understand the basics of the Composite pattern and try to see when it can be useful. We will also look at a toy application using composite pattern to get better understanding of the pattern. The example code in this article will be mainly for the illustration of this pattern and will be a not-so-real world example. The idea of this this article is to illustrate the concept of composite pattern only.


Many a times in our applications we encounter a scenario where we need to have a tree type data structure where we need to handle collections of collections in a seamless manner.If we have a scenario where we have a nested collections i.e. a tree data structure and the calling code need to handle this data structure in such a way that there should be no difference in handling an individual item that is contained inside the tree i.e. single item or a tree node containing multiple items i.e. a composite.

One classic example that we can think of for this is our UI controls. Every control is a UIControl be it form or be it a button. But a form could contain other controls like buttons and text boxes. So the form is a composite control(of type UIControl) that contains a lot of other controls(of type UIControl). if we drag a Panel control on form that Panel control itself could contain other controls and forms now contains panel control. So all of these objects are of type UIControl but few of them exist independently like button and few actually contain other controls. But from the Rendering and event handling perspective all these controls are treated same. That would mean that code for rendering and event handling is treating the composite objects i.e. form containing other controls and the button controls all the same.

In short, Composite patterns should be used whenever we want the calling code(clients) to treat the compositions of objects and individual objects in the same manner.

Before getting further to understanding this pattern using example, lets look at the Gang of Four definition and class diagram for this pattern.

Compose objects into tree structure to represent part-whole hierarchies.Composite lets client treat individual objects and compositions of objects uniformly

Few things that I want to explicitly call out(from OO perspective) before understanding what each component in this diagram is.

  1. A Composite is a Component.
  2. A Leaf is a Component.
  3. A Composite has Components.

Let us try to understand each component of this class diagram.

  • Component: This is the contract/interface for the objects in the composition. In some cases this could also implements default behavior common to all derived classes i.e. Composite and Leaf
  • Leaf: This is the object that has no objects of Component type inside this i.e. no children.
  • Composite: This class contains other Component as children and defines contract/interface required for all Composite types down the hierarchy.
  • Client: Used the Leaf and Composite type objects in exact same way.

Using the code

To understand this better let’s try to implement a simple application where we will see how this pattern can help us manage nested collections and data in tree structure in a seamless manner.

Note: The focus of this example will be to illustrate the composite pattern and how using this makes the calling code in client cleaner. There are some shortcuts taken on code quality and some design choices. Please ignore that part as the idea is only to focus on the pattern. I will make a note of these things as and when we see the code as improvement note.

So to illustrate this pattern lets take a problem where we have an organization and this organization let the employees subscribe to various types of training subscriptions. The small module that we will be creating is to find the cost implication on the organization due to this for a given employee. If we look at a typical organization, there will be employees and there will be managers. The managers also have managers. So an organization structure is of a tree type.

The client will try to retrieve the subscription cost for an employee. If the Employee is not a manager, the cost will be for only his subscriptions but if he is a manager, the cost will be for his subscriptions and the cost of subscription for his team members. Let;s try to work on this problem statement and see how we can leverage composite pattern to design the solution in such a way that client can retrieve the cost of subscriptions in same way irrespective of the employee being a manager or not.

Let’s visualize the proposed solution before looking at the code:

Let’s start by creating a simple enum SubscriptionType and a class Subscription that will track the type of the subscription and a class to store the subscription details.

Improvement Note: This is not the best way to design this class but we are keeping the code simple just to focus on the parts that are relevant for this pattern. For now this class will just help us encapsulate the subscription information.

Now that we have the subscription class ready, lets try to create the Component part of the pattern. For this, let’s create an interface of type IEmployee.

This interface provides a contract that all Leaf and Composite types should implement. It keeps track of Employee specific attributes and list of subscriptions. It also has the methods to retrieve the subscription information for a given employee.

Now let’s look at our Leaf class i.e. Employee.

Improvement Note: This class has all the same members that are in our IEmployee interface. One way to implement this could have been to either have an abstract class instead of interface where the abstract class could provide the default implementation of the GetCost and GetSubscriptionCount methods.

Now that we have the Employee class i.e. the Leaf node ready, let’s see how we can create the Manager class.

If we look at the Manager class, we can see that it is a composite containing a collection of IEmployees. Also, the GetCost and GetSubscriptionCount count method are overriden in this class to handle the cost calculations based on the Manager's own subscriptions and his team member Employee's subscriptions.

The beauty of this code is that the caller will use the same logic to get the cost of the subscription from Manager and Employee object. The handling of the sub nodes inside the composite is totally encapsulated inside the Composite object itself.

Improvement Note: The code shown here is just to illustrate the composite pattern only as we can clearly see that there is a “ <em>is-a</em>” relationship between Manager and Employee. So why are we modeling them as separate classes. it is just to illustrate the pattern as is. In ideal case, we should have the Employee as base class of Manager. Or better, single Employee class can be used and we can use state pattern to identify if the object at the moment is Employee or Manager.

Now that we have the classes ready to be consumed. Let’s look at the client code on how it is consuming the classes to calculate cost.

Note: The client code is rather messy and lengthy just because the setup code that is required to create subscription and employee classes. First let me post the complete client code and then I will show how the same logic is being used to display cost information irrespective of the object being of Employee or Manager type.

Most of the above shown code deals with setting up the objects and wiring up the objects to assign subscriptions to employees and creating employee manager relationship. But the code that is of our interest is encapsulated inside the function PrintCostDetails.

We will see how this code will remain the same and it will print the subscription cost of Employee and Manager seamlessly. Internally our Composite class will handle all the business logic dealing with the composed objects. Let’s run the code and see the output.

In this example we are only showing 1 level of hierarchy but the design is in place to handle N level of hierarchy too. The Composite class and the Client class need to change a bit and we will be able to handle any level of hierarchy with this code.

Point of Interest

In this article we have looked at the basics of composite pattern and how we can use this pattern to effectively manage the tree data that is in tree structure and nested collections. We have used a rather contrived example just to demonstrate this pattern. This article has been written from an absolute beginner’s perspective. I hope this has been informative.

Download sample code here: CompositeExample