zoukankan      html  css  js  c++  java
  • 组合模式【大话设计模式DEMO】

    组合模式将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
    整体与部分可以被一致对待。(看上去也有递归的感觉)

    类设计图:

    DEMO代码:

    代码
    class RunCompositePattern
    {

    static void Main(string[] args)
    {
    Composite root
    = new Composite("root");
    root.Add(
    new Leaf("A"));
    root.Add(
    new Leaf("B"));

    Composite comp
    = new Composite("Compostie X");
    comp.Add(
    new Leaf("Leaf XA"));
    comp.Add(
    new Leaf("Leaf XB"));

    root.Add(comp);

    Composite comp2
    = new Composite("Compostie XY");
    comp2.Add(
    new Leaf("Leaf XYA"));
    comp2.Add(
    new Leaf("Leaf XYB"));

    comp.Add(comp2);

    root.Add(
    new Leaf("C"));
    Leaf leaf
    = new Leaf("D");
    root.Add(leaf);
    root.Remove(leaf);
    root.Display(
    1);
    Console.ReadKey();

    }
    }

    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(
    "不能为叶子节点添加子元素");
    }

    public override void Remove(Component c)
    {
    Console.WriteLine(
    "不能从叶子节点删除子元素");
    }
    public override void Display(int depth)
    {
    Console.WriteLine(
    new String('-', depth) + Name);
    }
    }

    class Composite : Component
    {
    private List<Component> children = new List<Component>();
    public Composite(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 item in children)
    {
    item.Display(depth
    + 2);
    }
    }
    }

    运行结果:

  • 相关阅读:
    word无法启动转换器RECOVR32.CNV
    win10致远OA显示正在转换。请稍等,不能获取office文件转换服务
    视频编辑剪辑软件
    软件质量属性——可修改性
    《架构之美》阅读笔记五
    架构漫谈一
    《架构之美》阅读笔记三
    《架构之美》阅读笔记二
    机器学习七讲——最优化
    机器学习六讲——降维
  • 原文地址:https://www.cnblogs.com/shineqiujuan/p/1700384.html
Copyright © 2011-2022 走看看