二十一.组合模式

组合模式:

       Composite:将对象组合成树形结构以表示“部分-整体“的层次结构。

       组合模式使得用户对单个对象和组合对象的使用具有一致性。

 

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

 

Demo

       //为组合中的对象声明接口,用于访问和管理子部件,添加移除功能

    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("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);

       }

}

 

 

 

       //定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关的操作

    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 voidRemove(Component c)

       {

           children.Remove(c);

       }

       public override void Display(int depth)

       {

           Console.WriteLine(new string('-', depth) + name);

           foreach (Component co in children)

           {

                co.Display(depth+2);

           }

       }

}

 

 

       class Program

    {

       static void Main(string[] args)

       {

           Composite root = new Composite("root");

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

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

 

           Composite comp = new Composite("Composite X");

           comp.Add(new Leaf("Leaf A"));

           comp.Add(new Leaf("Leaf B"));

 

           root.Add(comp);

 

            Composite comp2 = newComposite("Composite XY");

           comp2.Add(new Leaf("Leaf XYA"));

           comp2.Add(new Leaf("Leaf XYB"));

 

           comp.Add(comp2);

 

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

 

           Leaf leaf = new Leaf("Leaf D");

           root.Add(leaf );

           root.Remove(leaf );

 

           root.Display(1);

 

           Console.ReadKey();

       }

    }

 

 

posted @ 2010-09-01 20:31  耀哥  阅读(197)  评论(0编辑  收藏  举报