Holi Sale. Get upto 40% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
Composite Design Pattern

Composite Design Pattern

23 Aug 2022
Intermediate
94.6K Views
4 min read
Learn via Video Course & by Doing Hands-on Labs

⭐ .NET Design Patterns Course: Design Patterns in C# Online Training

Composite pattern falls under Structural Pattern of Gang of Four (GOF) Design Patterns in .Net. Composite Pattern is used to arrange structured hierarchies. In this article, I would like to share what is a composite pattern and how is it work?

What is Composite Pattern

Composite pattern is used to separate abstraction from its implementation so that both can be modified independently.

Composite pattern is used when we need to treat a group of objects and a single object in the same way. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchies.

This pattern creates a class contains a group of its own objects. This class provides ways to modify its group of the same objects.

Composite Pattern - UML Diagram & Implementation

The UML class diagram for the implementation of the composite design pattern is given below:

The classes, interfaces, and objects in the above UML class diagram are as follows:

  1. Component

    This is an abstract class containing members that will be implemented by all object in the hierarchy. It acts as the base class for all the objects within the hierarchy

  2. Composite

    This is a class which includes Add, Remove, Find and Get methods to do operations on child components.

  3. Leaf

    This is a class which is used to define leaf components within the tree structure means these cannot have children.

C# - Implementation Code

public interface Component
{
 void Operation();
}

public class Composite : Component, IEnumerable
{
 private List _children = new List();
 public void AddChild(Component child)
 {
 _children.Add(child);
 }
 public void RemoveChild(Component child)
 {
 _children.Remove(child);
 }
 public Component GetChild(int index)
 {
 return _children[index];
 }
 public void Operation()
 {
 string message = string.Format("Composite with {0} child(ren)", _children.Count);
 Console.WriteLine(message);
 }
 public IEnumerator GetEnumerator()
 {
 foreach (Component child in _children)
 yield return child;
 }
 IEnumerator IEnumerable.GetEnumerator()
 {
 return GetEnumerator();
 }
}
public class Leaf : Component
{
 public void Operation()
 {
 Console.WriteLine("Leaf");
 }
}

Composite Pattern - Example

Who is what?

The classes, interfaces, and objects in the above class diagram can be identified as follows:

  1. IEmployed - Component Interface.

  2. Employee- Composite Class.

  3. Contractor- Leaf Class.

C# - Sample Code

/// <summary>
/// The 'Component' Treenode
/// </summary>
public interface IEmployed
{
 int EmpID { get; set; }
 string Name { get; set; }
}

/// <summary>
/// The 'Composite' class
/// </summary>
public class Employee : IEmployed, IEnumerable<IEmployed>
{
 private List<IEmployed> _subordinates = new List<IEmployed>();

 public int EmpID { get; set; }
 public string Name { get; set; }

 public void AddSubordinate(IEmployed subordinate)
 {
 _subordinates.Add(subordinate);
 }

 public void RemoveSubordinate(IEmployed subordinate)
 {
 _subordinates.Remove(subordinate);
 }

 public IEmployed GetSubordinate(int index)
 {
 return _subordinates[index];
 }

 public IEnumerator<IEmployed> GetEnumerator()
 {
 foreach (IEmployed subordinate in _subordinates)
 {
 yield return subordinate;
 }
 }

 IEnumerator IEnumerable.GetEnumerator()
 {
 return GetEnumerator();
 }
}

/// <summary>
/// The 'Leaf' class
/// </summary>
public class Contractor : IEmployed
{
 public int EmpID { get; set; }
 public string Name { get; set; }
}

class Program
{
 static void Main(string[] args)
 {
 Employee Rahul = new Employee { EmpID = 1, Name = "Rahul" };
 
 Employee Amit = new Employee { EmpID = 2, Name = "Amit" };
 Employee Mohan = new Employee { EmpID = 3, Name = "Mohan" };

 Rahul.AddSubordinate(Amit);
 Rahul.AddSubordinate(Mohan);

 Employee Rita = new Employee { EmpID = 4, Name = "Rita" };
 Employee Hari = new Employee { EmpID = 5, Name = "Hari" };

 Amit.AddSubordinate(Rita);
 Amit.AddSubordinate(Hari);

 Employee Kamal = new Employee { EmpID = 6, Name = "Kamal" };
 Employee Raj = new Employee { EmpID = 7, Name = "Raj" };
 
 Contractor Sam = new Contractor { EmpID = 8, Name = "Sam" };
 Contractor tim = new Contractor { EmpID = 9, Name = "Tim" };

 Mohan.AddSubordinate(Kamal);
 Mohan.AddSubordinate(Raj);
 Mohan.AddSubordinate(Sam);
 Mohan.AddSubordinate(tim);

 Console.WriteLine("EmpID={0}, Name={1}", Rahul.EmpID, Rahul.Name);

 foreach (Employee manager in Rahul)
 {
 Console.WriteLine("\n EmpID={0}, Name={1}", manager.EmpID, manager.Name);

 foreach (var employee in manager)
 {
 Console.WriteLine(" \t EmpID={0}, Name={1}", employee.EmpID, employee.Name);
 }
 }
 Console.ReadKey();
 }
} 

composite Pattern Demo - Output

When to use it?

  1. Hierarchical representations of objects are required.

  2. A single object and a group of objects should be treated in the same way.

  3. The Composite pattern is used when data is organized in a tree structure (for example directories in a computer).

Read More Articles Related to Design patterns
What do you think?

I hope you will enjoy the composite Pattern while designing your software. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this