组合模式

组合模式又叫部分整体模式,它创建了对象组的树形结构,将对象组合成树状结构以表示“整体-部分”的层次关系。

组合模式依据树形结构来组合对象,用来表示部分以及整体的层次。

组合模式使得用户对单个对象和组合对象的访问具有一致性,即:组合能让客户以一致的方式处理个别对象以及组合对象。

    //Component为组合中的对象声明接口,在适当情况下,实现所有类共有接口的默认行为,声明一个接口用于访问和管理Component的子部件
   abstract class Component
    {
       protected string name;
       public Component(string name)
       {
           this.name = name;
       }
       public abstract void Add(Component c);//通常都用Add和Remove方法来提供增加或移除树叶或树枝的功能
       public abstract void Remove(Component c);
       public abstract void Display(int depth); 
   }

    //Component为组合中的对象声明接口,在适当情况下,实现所有类共有接口的默认行为,声明一个接口用于访问和管理Component的子部件
   abstract class Component
    {
       protected string name;
       public Component(string name)
       {
           this.name = name;
       }
       public abstract void Add(Component c);//通常都用Add和Remove方法来提供增加或移除树叶或树枝的功能
       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("Cannot add to a leaf");
        }
        //由于叶子没有再增加分支和树叶,所有add和Remove方法实现它没有意义,但这样做可以消除叶子节点和树枝节点对象在抽象层次的区别,
        //他们具备完全一致的接口。
        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);
        }
    }

        //我感觉组合模式有点像我们在在web上的菜单栏,一级菜单下可以有二级菜单,二级菜单下还能拓展出三级菜单。
        static void Main(string[] args)
        {
            Composite root = new Composite("root");//生成树根root,根上长出树叶LeafA和LeafB
            root.Add(new Leaf("Leaf A"));
            root.Add(new Leaf("Leaf B"));

            Composite comp = new Composite("Composite X");//根上长出分枝Composite X,分枝上也有两叶LeafXA和LeafXB
            comp.Add(new Leaf("Leaf XA"));
            comp.Add(new Leaf("Leaf XB"));
            root.Add(comp);

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

            root.Add(new Leaf("Leaf C"));

            Leaf leaf = new Leaf("Leaf D");
            root.Add(leaf);
            root.Remove(leaf);            
            Console.Read();
        }
原文地址:https://www.cnblogs.com/vichin/p/11598501.html