zoukankan      html  css  js  c++  java
  • 组合模式

    场景:

    1.希望把对象表示成部分—整体层次结构;

    2.希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中所有对象。

    UML图:

    示例代码:

        public 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);
        }
        public class Leaf:Component
        {
            public override void Add(Component c)
            {
                Console.WriteLine("Cannot add to a leaf");
            }
    
            public override void Remove(Component c)
            {
                Console.WriteLine("Cannot remove from a leaf");
            }
    
            public override void Display(int depth)
            {
                Console.WriteLine(new String('-', depth) + _name);
            }
    
            public Leaf(string name) : base(name)
            {
            }
        }
        public class Composite:Component
        {
            private List<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 component in _children)
                {
                    component.Display(depth + 2);
                }
            }
    
            public Composite(string name) : base(name)
            {
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                Composite root = new Composite("root");
                root.Add(new Leaf("Leaf A"));
                root.Add(new Leaf("Leaf B"));
    
                Composite comp = new Composite("Composite X");
                comp.Add(new Leaf("Leaf XA"));
                comp.Add(new Leaf("Leaf XB"));
    
                root.Add(comp);
                root.Add(new Leaf("Leaf C"));
    
                // Add and remove a leaf
                Leaf leaf = new Leaf("Leaf D");
                root.Add(leaf);
                root.Remove(leaf);
    
                // Recursively display tree
                root.Display(1);
            }
        }
  • 相关阅读:
    垂死挣扎-3
    垂死挣扎-2
    垂死挣扎-1
    【互联网考试系列-1】进程与线程
    【iOS基础学习随笔-2】SQLite的使用
    【iOS面试系列-2】多线程中同步、异步和串行、并行之间的逻辑关系(必考,必须掌握)
    docker
    给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
    621. 任务调度器
    204. 计数质数
  • 原文地址:https://www.cnblogs.com/chenyishi/p/9116918.html
Copyright © 2011-2022 走看看