設計模式-組合模式

abstract class Component
    {
        protected string name;
        public Component(string _name)
        {
            name = _name;
        }
        public abstract void Add(Component c);
        public abstract void Remove(Component c);
        public abstract void Display(int depth);
    }

    class Leaf : Component
    {
        public Leaf(string _name) : base(_name)
        {
        }

        public override void Add(Component c)
        {
            Console.WriteLine("葉子不允許添加");
        }        

        public override void Remove(Component c)
        {
            Console.WriteLine("葉子不允許移除子節點");
        }

        public override void Display(int depth)
        {
            Console.WriteLine(new string('-',depth)+name);
        }
    }

    class Composite : Component
    {
        List<Component> childList = new List<Component>();
        public Composite(string _name) : base(_name)
        {
        }

        public override void Add(Component c)
        {
            childList.Add(c);
        }

        public override void Remove(Component c)
        {
            childList.Remove(c);
        }
        public override void Display(int depth)
        {
            Console.WriteLine(new string('-', depth) + name);
            foreach (var item in childList)
            {
                item.Display(depth + 2);
            }
        }
    }
        //前端
        static void Main(string[] args)
        {
            Component c = new Composite("總公司");
            Component c1 = new Leaf("財務部");
            Component c2 = new Leaf("人事部");
            Component c3 = new Composite("南京分公司");

            c.Add(c1);
            c.Add(c2);
            c.Add(c3);
            c3.Add(c1);
            c3.Add(c2);
            c1.Add(c2);
            c3.Display(1);
            Console.ReadLine();
        }

總結:當需求是體現了部分與整體的層次結構時,但是可以忽略單個對象與組合對象的不同,而統一使用結構中的所有對象的時候,可以 用組合模式。
優點:
1、對象可以無限組合,可以使用單個對象的地方就可以使用組合對象。
2、可以一致的使用單個對象或是組合對象。
3、可以很輕鬆的擴展
缺點:
1、不直觀;
2、設計太抽象,應對複雜業務時,使用組合模式得三思。
3、很難對各層次中的對象加特別處理。

設計模式-組合模式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章