快上网专注成都网站设计 成都网站制作 成都网站建设
成都网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

设计模式-组合模式-创新互联

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 childList = new List();
        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、很难对各层次中的对象加特别处理。

创新互联建站网站建设公司一直秉承“诚信做人,踏实做事”的原则,不欺瞒客户,是我们最起码的底线! 以服务为基础,以质量求生存,以技术求发展,成交一个客户多一个朋友!专注中小微企业官网定制,成都网站设计、成都网站制作,塑造企业网络形象打造互联网企业效应。

设计模式-组合模式

创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。


本文题目:设计模式-组合模式-创新互联
网页链接:http://6mz.cn/article/iegce.html

其他资讯