using System; using System.Collections.Generic; using System.Text; using System.Collections; ///Composite(组合)模式将对象组合成树形结构以表示“部分-整体”的层次结构,对单个对象和复合对象的使用具有一致性。 ///add by jzh 2007-04-15 namespace DesignPattern { abstract class Component { protected string strName; public Component(string name) { strName = name; } abstract public void Add(Component c); public abstract void DumpContents(); } class Composite : Component { private ArrayList ComponentList = new ArrayList(); public Composite(string s) : base(s) { } override public void Add(Component c) { ComponentList.Add(c); } public override void DumpContents() { Console.WriteLine("Node: {0}", strName); foreach (Component c in ComponentList) { c.DumpContents(); } } } class Leaf : Component { public Leaf(string s) : base(s) { } override public void Add(Component c) { Console.WriteLine("Cannot add to a leaf"); } public override void DumpContents() { Console.WriteLine("Node: {0}", strName); } } public class Client { Component SetupTree() { Composite root = new Composite("root-composite"); Composite parentcomposite; Composite composite; Leaf leaf; parentcomposite = root; composite = new Composite("第一层 - first sibling - composite"); parentcomposite.Add(composite); leaf = new Leaf("第一层 - second sibling - leaf"); parentcomposite.Add(leaf); parentcomposite = composite; composite = new Composite("第二层 - first sibling - composite"); parentcomposite.Add(composite); composite = new Composite("第二层 - second sibling - composite"); parentcomposite.Add(composite); parentcomposite = composite; leaf = new Leaf("第三层 - first sibling - leaf"); parentcomposite.Add(leaf); leaf = new Leaf("第三层 - second sibling - leaf"); parentcomposite.Add(leaf); composite = new Composite("第三层 - third sibling - composite"); parentcomposite.Add(composite); return root; } public static void Main(string[] args) { Component component; Client c = new Client(); component = c.SetupTree(); component.DumpContents(); Console.ReadLine(); } } }