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
  • 相关阅读:
    c++虚继承
    linux常用命令大全
    数据库三大范式最通俗解释
    PG数据库空间大小及数据库对象占用空间大小
    Oracle表分区详解
    Excel数据导入PG库,字符串正则表达式
    Oracle 执行计划
    ASP.NET MVC5框架揭秘 学习笔记01
    .NET简单学习
    蓝桥杯_算法训练_ALGO10_集合运算
  • 原文地址:https://www.cnblogs.com/liurui/p/5538114.html
Copyright © 2011-2022 走看看