The composite pattern allows you to set up a tree structure and each level has to perform the task. It is having the relation and composite and the leaf level. Leaf level will be the last level of that structure.
You can take the example of organization chart where we have manager at the top level and in Manager we have two senior lead and below two senior lead one is having one lead and two associates and another senior lead is having two associate only.
Now demonstrating the example how in code level it will behave.
Creating the employee interface which is having the ShowReport method. This employee class will call in both the classes of supervisor and associates.
IEmployee – Is interface and having the Show report method.
Supervisor – Is class which is having the method of adding sub ordinates.
Assosiates – Is a class, which will maintain the Designation and name like supervisor.
It will be like below;
namespace CompositePattern
{
class Program
{
static void Main(string[] args)
{
Assosiates a = new Assosiates("Tom", "assosiate");
Supervisor b = new Supervisor("Mary", "supervisor");
Supervisor c = new Supervisor("Jerry", "supervisor");
Supervisor d = new Supervisor("Bob", "supervisor");
Assosiates e = new Assosiates("Jimmy", "assosiate");
//set up the relationships
b.AddSubordinate(a); //Tom works for Mary
c.AddSubordinate(b); //Mary works for Jerry
c.AddSubordinate(d); //Bob works for Jerry
d.AddSubordinate(e); //Jimmy works for Bob
//Showing the reports from top level
if (c is IEmployee)
(c as IEmployee).ShowReport();
}
}
///
/// Creating employee class to show report
///
public interface IEmployee
{
void ShowReport();
}
public class Supervisor : IEmployee
{
private string name;
private string designation;
private List<IEmployee> subordinate = new List<IEmployee>();
public Supervisor(string name, string designation)
{
this.name = name;
this.designation = designation;
}
void IEmployee.ShowReport()
{
Console.WriteLine(name + " showed level of " + designation);
//show all the subordinate's happiness level
foreach (IEmployee i in subordinate)
i.ShowReport();
}
public void AddSubordinate(IEmployee employee)
{
subordinate.Add(employee);
}
}
public class Assosiates : IEmployee
{
private string name;
private string designation;
public Assosiates(string name, string designation)
{
this.name = name;
this.designation = designation;
}
void IEmployee.ShowReport()
{
Console.WriteLine("--" + name + " showed level of " + designation);
}
}
}
Get the output from the top level of the organization here Jerry is on the top level.
No comments:
Post a Comment