Friday, June 7, 2013

Composite design pattern in c#

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

**The composite design pattern allows you 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.
     * 
     * The composite pattern classifies each element in the tree as a composite or a leaf. 
     * A composite means that there can be other elements below it, whereas a leaf cannot have any elements below it. 

     * Therefore the leaf must be at the very bottom of the tree.

class Program
    {
        static void Main(string[] args)
        {
            Worker a = new Worker("Worker Tom", 5);
            Supervisor b = new Supervisor("Supervisor Mary", 6);
            Supervisor c = new Supervisor("Supervisor Jerry", 7);
            Supervisor d = new Supervisor("Supervisor Bob", 9);
            Worker e = new Worker("Worker Jimmy", 8);

            //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

            //Jerry shows his happiness and asks everyone else to do the same
            if (c is IEmployee)
                (c as IEmployee).ShowHappiness();

            Console.ReadKey();
        }
    }
    public interface IEmployee
    {
        void ShowHappiness();
    }
    public class Worker : IEmployee
    {
        private string name;
        private int happiness;

        public Worker(string name, int happiness)
        {
            this.name = name;
            this.happiness = happiness;
        }
        public void ShowHappiness()
        {
            Console.WriteLine(name + " showed happiness level of " + happiness);
        }
    }
    public class Supervisor : IEmployee
    {
        private string name;
        private int happiness;
        private List<IEmployee> subOrdinate = new List<IEmployee>();

        public Supervisor(string name, int happiness)
        {
            this.name = name;
            this.happiness = happiness;
        }

        public void ShowHappiness()
        {
            Console.WriteLine(name + " showed happiness level of " + happiness);
            foreach (IEmployee i in subOrdinate)
                i.ShowHappiness();
        }
        public void AddSubordinate(IEmployee employee)
        {
            subOrdinate.Add(employee);
        }

    }

No comments:

Post a Comment