Please enable Javascript to correctly display the contents on Dot Net Tricks!

Composite Design Pattern - C#

 Print 
  Author : Shailendra Chauhan
Posted On : 13 Jul 2013
Total Views : 53,301   
Updated On : 26 Sep 2016
 

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 share what is composite pattern and how is it work?

What is Composite Pattern

Composite pattern is used to separate an 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 group of its own objects. This class provides ways to modify its group of 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).

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.



Free Interview Books
 
COMMENTS
20 SEP
MEAN Stack (Online)
07:00 AM-09:00 AM IST
20 SEP
ASP.NET MVC with Angular4 (Online)
9:00PM- 11:00PM IST(+5:30GMT)
16 SEP
Angular2 and Angular4 (Online)
08:00 AM-10:00 AM IST(+5.30 GMT)
16 SEP
Microsoft Azure Infrastructure Solutions (Online)
08:00 PM-11:00 PM IST / 9:30 AM-12:30 PM CST
7 SEP
ASP.NET MVC with Angular4 (Online)
09:00 PM to 11:00 PM IST (+5:30 GMT)
22 AUG
ASP.NET Core with Angular4 (Online)
07:00 AM - 9:00 AM IST(+5:30 GMT)
19 AUG
MEAN Stack 2 (Online)
5:30 Pm - 7:00 PM IST (+5:30 GMT)
19 AUG
ASP.NET MVC with Angular4 (Online)
10:30 Am to 12:30 PM IST (+ 5:30 GMT)
19 AUG
NodeJS with Angular4 (Classroom)
04:00 PM to 07:00 PM IST (+5:30 GMT)
12 AUG
ASP.NET MVC with Angular4 (Classroom)
11:30 AM - 1:30 PM IST (+5:30GMT)
15 JUL
ASP.NET MVC with Angular4 (Online)
03:30 PM - 05:30 PM IST(+5.30 GMT)
LIKE US ON FACEBOOK
 
+