温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

设计模式-组合模式

发布时间:2020-08-05 23:01:36 来源:网络 阅读:284 作者:全嗲吉祥 栏目:编程语言
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、很难对各层次中的对象加特别处理。

设计模式-组合模式

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI