设计模式-组合模式-成都快上网建站

设计模式-组合模式

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、很难对各层次中的对象加特别处理。

创新互联公司服务项目包括石泉网站建设、石泉网站制作、石泉网页制作以及石泉网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,石泉网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到石泉省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!

设计模式-组合模式


本文题目:设计模式-组合模式
URL分享:http://kswjz.com/article/jidgoe.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流