zoukankan      html  css  js  c++  java
  • 设计模式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
  • 相关阅读:
    JQuery checkbox全选多次点击后无效解决方法
    mongodb更新数据
    EasyUI--datebox设置默认时间
    转载:MyEclipse中防止代码格式化时出现换行的情况的设置
    Java 多维数组 按某列 排序
    Java Entry使用
    matlab使用reshape时按照列优先原则取元素和摆放元素
    boost--signal
    boost--function
    boost--bind
  • 原文地址:https://www.cnblogs.com/liurui/p/5538114.html
Copyright © 2011-2022 走看看