组合模式

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

举例实现公司,分公司,部门等的组合关系:

实现声明组合中的对象接口,在适当的情况下实现所有类共有接口的默认行为,声明一个接口用户访问和管理所有的子部件:

    /// <summary>
    /// 在接口中声明所有用来管理子对象的方法,包括Add和Remove等
    /// </summary>
    abstract class Component
    {
        
        protected string Name { get; set; }

        public Component(string name)
        {
            this.Name = name;
        }

        public abstract void Add(Component c);
        public abstract void Delete(Component c);
        public abstract void Display();
        public abstract void Display(int depth);
    }

下面定义子部件行为,在Component接口中实现有关的操作:

    class Composite:Component
    {
        protected List<Component> children = new List<Component>();

        public Composite(string name)
            : base(name)
        { }

        public override void Add(Component c)
        {
            children.Add(c);
        }

        public override void Delete(Component c)
        {
            children.Remove(c);
        }

        public override void Display()
        {
            Console.WriteLine(this.Name);

            foreach (Component c in children)
            {
                c.Display(1);
            }

        }

        public override void Display(int depth)
        {
            Console.WriteLine(new string('-', depth)+this.Name);

            foreach (Component c in children)
            {
                c.Display(depth + 1);
            }
        }

       
    }

 客户端使用组合模式构建对象集合:

            Composite root = new Composite("root");

            Composite A = new Composite("A");
            root.Add(A);

            Composite B = new Composite("B");
            root.Add(B);

            Component A1 = new Composite("A1");
            A.Add(A1);

            root.Display();

执行结果如下:

root
-A
--A1
-B

总体而言,当需求中是体现部分和整体层次的结构时,以及你希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时,就应该考虑组合模式。

  

 

 

原文地址:https://www.cnblogs.com/angela217/p/5454269.html