• 设计模式9-组合模式


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

     1 namespace DesignModel.组合模式
     2 {
     3     abstract class Components
     4     {
     5         protected string Name { get; set; }
     6         public Components(string name)
     7         {
     8             Name = name;
     9         }
    10         public abstract void Add(Components c);
    11 
    12         public abstract void Remove(Components c);
    13 
    14         public abstract void Display(int depth);
    15     }
    16 
    17 
    18     class Compsite : Components
    19     {
    20         private List<Components> children = new List<Components>();
    21         public Compsite(string name) : base(name)
    22         {
    23         }
    24 
    25         public override void Add(Components c)
    26         {
    27             children.Add(c);
    28         }
    29         public override void Remove(Components c)
    30         {
    31             children.Remove(c);
    32         }
    33 
    34         public override void Display(int depth)
    35         {
    36             //....
    37             foreach (var item in children)
    38             {
    39                 item.Display(depth+2);
    40             }
    41         }
    42 
    43     }
    44 
    45     class Leaf : Components
    46     {
    47         public Leaf(string name) : base(name)
    48         {
    49 
    50         }
    51 
    52         public override void Add(Components c)
    53         {
    54             ///叶子节点没有下级操作,所以可以考虑将操作方法移至树枝节点类里面去。但在client使用时需要区分。
    55             Console.WriteLine("叶子节点不能再增加下级");
    56         }
    57         public override void Remove(Components c)
    58         {
    59             Console.WriteLine("叶子节点没有可移除的下级");
    60         }
    61 
    62         public override void Display(int depth)
    63         {
    64             //......current is ....
    65         }
    66     }
    67 }
    68 
    69  static void 组合模式()
    70         {
    71             Components root = new Compsite("root");
    72             root.Add(new Leaf("A"));
    73             root.Add(new Leaf("B"));//增加叶节点(再无下级)
    74 
    75             Compsite childroot = new Compsite("childroot");
    76             childroot.Add(new Leaf("A1"));
    77             childroot.Add(new Leaf("B2"));
    78 
    79             root.Add(childroot);//增加子节点
    80 
    81             root.Display(1);
    82 
    83 
    84         }
    View Code
  • 相关阅读:
    如何在iPhone 显示一个 星级评分
    Swift调用Objective-C
    Swift中的注释以及表达式
    Swift常量和变量以及命名规范
    Swift标识符和关键字
    使用Playground编写第一个Swift程序
    Cocos2d-x实例:设置背景音乐与音效-设置场景实现
    Cocos2d-x实例:设置背景音乐与音效-HelloWorld场景实现
    Cocos2d-x实例:设置背景音乐与音效- AppDelegate实现
    Cocos2d-x中背景音乐播放暂停与继续
  • 原文地址:https://www.cnblogs.com/liurui/p/5538114.html
Copyright © 2020-2023  润新知