zoukankan      html  css  js  c++  java
  • 设计模式之组合模式

    定义:将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使用户对单个对象和组合对象的使用具有一致性。

    类:

        abstract class Component
        {
            protected string name;
            public Component(string name)
            {
                this.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) { }
            public override void Remove(Component c) { }
            public override void Display(int depth)
            {
                Console.WriteLine(new string('-', depth) + name);
            }
        }
        class Compsite : Component
        {
            private List<Component> children = new List<Component>();
            public Compsite(string name) :base(name){ }
            public override void Add(Component c)
            {
                children.Add(c);
            }
            public override void Remove(Component c)
            {
                children.Remove(c);
            }
            public override void Display(int depth)
            {
                Console.WriteLine(new string('-', depth) + name);
                foreach (Component c in children)
                {
                    c.Display(depth + 2);
                }
            }
        }

    何时使用:

    当你发现需求中是体现部分与整体层次的结构时,以及你希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时。.net中的应用:TreeView和自定义控件(control基类中就有add和remove方法)

  • 相关阅读:
    设计模式之命令模式
    设计模式之访问者模式
    ES6入门之Generator函数
    ES6入门之Iterator和for...of
    c# TcpClient简易聊天工具
    Mvc Action可以通过jsonp方式调取
    Webbrowser 在web项目中的使用
    关于java post get请求Demo (请求c#iis接口)
    Jquery 引擎模板 -template详解
    Redis在windows下安装过程
  • 原文地址:https://www.cnblogs.com/luyujie/p/5580914.html
Copyright © 2011-2022 走看看