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)
        {
            Console.WriteLine("Leaf cannot add");
        }
    
        public override void Remove(Component c)
        {
            Console.WriteLine("Leaf cannot remove");
        }
    
        public override void Display(int depth)
        {
            Console.WriteLine(new string('-', depth) + name);
        }
    }
    
    class Composite : Component
    {
        public Composite(string name) : base(name) { }
    
        IList<Component> children = new List<Component>();
    
        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);
            }
        }       
    }
    
    // 业务代码:
    Composite root = new Composite("高新兴");
    Leaf gc = new Leaf("财务部");
    Leaf gi = new Leaf("IT 部");
    Leaf ghr = new Leaf("人力");
    
    root.Add(gc);
    root.Add(gi);
    root.Add(ghr);
    
    Composite pa = new Composite("平安事业部");
    Leaf pahr = new Leaf("人力");
                
    Composite payf = new Composite("研发");
    Leaf jg = new Leaf("交通");
    payf.Add(jg);
                
    pa.Add(pahr);            
    pa.Add(payf);
    
    root.Add(pa);
    
    root.Display(1);
    
    - Y 公司
    ---财务部
    ---IT 部
    ---人力
    --- X 事业部
    -----人力
    -----研发
    -------交通
    

    组合模式定义了基本对象和组合对象,基本对象可以被组合到更复杂的组合对象,而组合对象又可以被组合,不断递归;
    可以在各个基本对象中定义内部对继承的抽象类的实现,而用户并不需要知道是处理一个基本对象还是组合对象,因此用不着写一些判断语句。

  • 相关阅读:
    CAS 认证
    最近邻规则分类(k-Nearest Neighbor )机器学习算法python实现
    scikit-learn决策树的python实现以及作图
    module object has no attribute dumps的解决方法
    最新Flume1.7 自定义 MongodbSink 结合TAILDIR Sources的使用
    数据探索中的贡献度分析
    python logging模块按天滚动简单程序
    Flume性能测试报告(翻译Flume官方wiki报告)
    python apsheduler cron 参数解析
    python pyspark入门篇
  • 原文地址:https://www.cnblogs.com/MichaelLoveSna/p/14199101.html
Copyright © 2011-2022 走看看