溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

設(shè)計模式-組合模式

發(fā)布時間:2020-08-05 23:01:36 來源:網(wǎng)絡(luò) 閱讀:289 作者:全嗲吉祥 欄目:編程語言
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("葉子不允許移除子節(jié)點");
        }

        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("財務(wù)部");
            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();
        }

總結(jié):當(dāng)需求是體現(xiàn)了部分與整體的層次結(jié)構(gòu)時,但是可以忽略單個對象與組合對象的不同,而統(tǒng)一使用結(jié)構(gòu)中的所有對象的時候,可以 用組合模式。
優(yōu)點:
1、對象可以無限組合,可以使用單個對象的地方就可以使用組合對象。
2、可以一致的使用單個對象或是組合對象。
3、可以很輕松的擴展
缺點:
1、不直觀;
2、設(shè)計太抽象,應(yīng)對復(fù)雜業(yè)務(wù)時,使用組合模式得三思。
3、很難對各層次中的對象加特別處理。

設(shè)計模式-組合模式

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI