Popular Posts

There was an error in this gadget

Jan 10, 2013



This pattern allows to set up a tree structure and ask each element in the tree structure to perform a task. A typical tree structure would be a company organization chart, where the CEO is at the top and other employees at the bottom. After the tree structure is established, you can then ask each element, or employee, to perform a common operation.



   Fig:Simple Concept of composite pattern

Fig:Class UML of composite pattern



- Create a console project in visual studio
- Create Interface of named it IEmployee
IEmployee.cs


  public interface IEmployee
    {
        void ShowLevel();
    }


- Create a class Worker and implement IEmployee

public class Worker:IEmployee
    {
        private string name;
        private int level;

        public Worker(string name, int level)
        {
            this.name = name;
            this.level = level;
        }

        void IEmployee.ShowLevel()
        {
            Console.WriteLine(name + " Access Level:" + level);

        }
    }




- Create Admin class and implement IEmployee

public class Admin:IEmployee
    {
        private string name;
        private int level;
        private List<IEmployee> subLevelObj = new List<IEmployee>();
     

        public Admin(string name, int level)
        {
            this.name = name;
            this.level = level;
        }


        void IEmployee.ShowLevel()
        {
            Console.WriteLine(name + " Access level of:" + level);
            //show all sub level
            foreach (IEmployee i in subLevelObj)
                i.ShowLevel();
        }

        public void AddSubLevel(IEmployee employeeObj)
        {
            subLevelObj.Add(employeeObj);
        }

    }


 - In the programs.cs file

static void Main(string[] args)
        {
            Worker aObj = new Worker("Faruk",4);
            Admin bObj = new Admin("Omar", 7);
            Admin cObj = new Admin("Jubayer",9);
            Admin dObj = new Admin("Khalid",8);
            Worker eObj = new Worker("Miki",6);
            Worker fObj = new Worker("Rajib",5);

            //Now Setup the relations
            bObj.AddSubLevel(dObj); //khalid belongs to Omar
            dObj.AddSubLevel(eObj); //miki belongs to khalid
            cObj.AddSubLevel(bObj); //Omar belongs to Jubayer
            cObj.AddSubLevel(fObj); //Rajib belongs to Jubayer
            bObj.AddSubLevel(aObj); //Faruk belongs to Omar


            //Jubayer shows the lavel and ask everyont to do the same
            if (cObj is IEmployee)
                (cObj as IEmployee).ShowLevel();


            Console.ReadKey();
        }






No comments:

Post a Comment