神刀安全网

Design Patterns Simplified – Part Twelve (Composite)

I am here to continue the discussion around Design Patterns . Today, we will go through one of the structural design pattern called Composite.

Also in case, you have not had a look at our previous articles, go through the following link:

Before talking about its implementation let’s begin with defining it.

As per GOF guys, Composite pattern is defined as in the following.

“Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.”

Well! Let’s understand what they mean and where this pattern can be fit into.

In cases, when data is available in hierarchical format and both individual (leaf) and composite (non-leaf) objects are treated in the same way, composite pattern turns out to be the perfect fit.

For example, employee structure in an organization where leadership or CEO stands in the top followed by bunch of directors and managers and then the junior employees.

Design Patterns Simplified - Part Twelve (Composite)

In this case CEO, Directors and Managers are composite objects as they manage their subordinates, however, Employees or Junior Employees are the individual objects that appear in the leaf of the structure.

Another example could be file system structure in a computer where hierarchy can be formed right form root folder till the last file available.

Child controls in the Windows or Web forms can also be handled by Composite pattern as they also follow the below given hierarchy.

  • Form -> Panel ->TextBox
  • Form -> Panel ->Table ->TextBox
  • Form -> Table-> Label

Below is the UML of Composite pattern.

Design Patterns Simplified - Part Twelve (Composite)

Composite pattern has three key elements as following.

  • Component: This is the abstract class or interface containing methods that will be implemented by all the objects in the hierarchy.
  • Composite: This class keeps all the methods required to manage its child objects i.e. Add/Remove/Get and common method defined in Component.
  • Leaf: This class has only the common method defined in Component.

How Composite pattern works?

We will understand this by simple example.

Let’s start with creating Component which is the base for all the objects

///<summary>   /// The Component   ///</summary>   public interface IEmployee    {       void ShowYearsOfExperiance();   }   

In the above interface, we have declared ShowYearsOfExperience as its common to all the employees be the CEO, manager or junior.

Now we will create the Manager class which will be the composite class.

///<summary>   /// The Composite   ///</summary>   public class Manager: IEmployee   {       private string _empName       {           get;           set;       }       private float _yearsOfExperiance       {           get;           set;       }       private List < IEmployee > subordinates = newList < IEmployee > ();       public Manager(stringempName, floatyearsOfExperiance)       {           this._empName = empName;           this._yearsOfExperiance = yearsOfExperiance;       }       public void ShowYearsOfExperiance()       {           Console.WriteLine("Manager {0} has {1} number of years of experiance", _empName, _yearsOfExperiance);           foreach(IEmployeeempin subordinates)           {               emp.ShowYearsOfExperiance();           }       }       public void AddSubordinate(IEmployeeemp)       {           subordinates.Add(emp);       }       public void RemoveSubordinate(IEmployeeemp)       {           subordinates.Remove(emp);       }   }   

The above composite class has set of methods to handle operations related to subordinates apart from implementing common method (ShowYearsOfExperiance) defined in IEmployee.

Now time has come to create Leaf object class which will cater to junior employees.

///<summary>   /// The Leaf   ///</summary>   public class Junior Employee: IEmployee    {       private string _empName        {           get;           set;       }       private float _yearsOfExperiance {           get;           set;       }       public JuniorEmployee(stringempName, floatyearsOfExperiance)        {           this._empName = empName;           this._yearsOfExperiance = yearsOfExperiance;       }       public void ShowYearsOfExperiance()        {           Console.WriteLine("/tSubordinate {0} has {1} number of years of experiance", _empName, _yearsOfExperiance);       }   }   

So at this point, we are done with creating key components (Component/Composite/Leaf), now let’s see how client uses them.

Console.Title = "Composite pattern demo";   Console.Title = "Composite pattern demo";   //Create JuniorEmployee object   JuniorEmployeejEmp1 = newJuniorEmployee("Ramesh", 2);   JuniorEmployeejEmp2 = newJuniorEmployee("Suresh", 3);   JuniorEmployeejEmp3 = newJuniorEmployee("Manoj", 2.5 f);   //Create Manager object   Managermanager1 = newManager("Prakash", 8);   Managermanager2 = newManager("Pankaj", 8.5 f);   Console.WriteLine("Adding Subordinates...");   //Add Subordinate   manager1.AddSubordinate(jEmp1);   manager1.AddSubordinate(jEmp2);   manager2.AddSubordinate(jEmp3);   //Call the common method which will execute in hierarchical fashion.   manager1.ShowYearsOfExperiance();   manager2.ShowYearsOfExperiance();   Console.WriteLine("/nRemoving Subordinates...");   //Remove Subordinate   manager1.RemoveSubordinate(jEmp2);   manager2.RemoveSubordinate(jEmp3);   //Call the common method after removal   manager1.ShowYearsOfExperiance();   

Output:

Design Patterns Simplified - Part Twelve (Composite)

As you can see in the above output that how employee’s structure is getting shown in the hierarchical fashion using composite pattern.

Point to be noted here that Composite pattern assumes that both composite (i.e. Manager) and individual (JuniorEmployee) objects are used and accessed in similar way, this is the reason we extracted common behavior (YearsOfExperiance) and put in the Component (IComponent).

To summarize, composite pattern can be used in cases where hierarchical representation of objects are required and both individual and composite objects are treated in the same way.

Hope you have liked the article. Look forward to your comments/ suggestions.

Read more articles on Design Patterns

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Design Patterns Simplified – Part Twelve (Composite)

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮