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

Composite Design Pattern - C#

  Author : Shailendra Chauhan
Updated On : 26 Sep 2016
Total Views : 45,271   
Support : All C# & .Net
 

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.

YOU MIGHT LIKE
Free Interview Books
 
COMMENTS (0)
14 DEC
ASP.NET MVC with AngularJS Development (online)

MON-FRI 07:30 AM- 09:00 AM IST

Know More
5 DEC
AngularJS Development (online)

Mon - Fri 6:30 AM-7:30 AM IST

Know More
3 DEC
AngularJS Development (offline)

SAT,SUN     11:00 AM-12:30 PM IST

3 DEC
MEAN Stack Development (offline)

Sat, Sun     (09:30 AM-11:00 AM IST)

26 NOV
ASP.NET MVC with AngularJS Development (offline)

(SAT,SUN)     03:30 PM-05:00 PM IST

24 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     09:30 PM-11:00 PM IST

12 NOV
ASP.NET MVC with AngularJS Development (offline)

SAT,SUN     08:00 AM-09:30 AM

3 NOV
ASP.NET MVC with AngularJS Development (online)

MON-FRI     07:30 AM-09:00 AM IST

25 OCT
.NET Development (offline)

Mon-Fri     9:00 AM-11:00 AM IST

BROWSE BY CATEGORY
 
RECENT ARTICLES
SUBSCRIBE TO LATEST NEWS
 
LIKE US ON FACEBOOK
 

Professional Speaks

+