组合模式(Composite):将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。让可以可以一致地使用组合结构和单个对象。
Component:为组合中的对象声明接口,在适当情况下,实现所有类所有接口的默认行为。证明一个接口/用于访问和管理Component的子部件。
Leaf:在组合中表示叶节点的对象,叶节点没有子节点。
Composite:定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关的操作,比如增加Add和删除Remove。
需求中是体现部分与整体层次的结构时,以及希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象是,考虑使用组合模式。
Composite1.cs

using System;using System.Collections.Generic;using System.Text;//组合模式(Composite):将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个//对象和组合对象的使用具有一致性。让可以可以一致地使用组合结构和单个对象。//Component:为组合中的对象声明接口,在适当情况下,实现所有类所有接口的默认行为。证明一个接口//用于访问和管理Component的子部件。//Leaf:在组合中表示叶节点的对象,叶节点没有子节点。//Composite:定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关的操作,比如增加//Add和删除Remove。//需求中是体现部分与整体层次的结构时,以及希望用户可以忽略组合对象与单个对象的不同,统一地使用//组合结构中的所有对象是,考虑使用组合模式。namespace Composite{ class Composite1 { } //Component 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); } //Leaf class Leaf : Component { public Leaf(string name) : base(name) { } public override void Add(Component c) { Console.WriteLine("Cannnot add to a leaf"); } public override void Remove(Component c) { Console.WriteLine("Cannnot remove from a leaf"); } public override void Display(int depth) { Console.WriteLine(new String('-', depth) + name); } } //Composite class Composite : Component { private List<Component> chilidren = new List<Component>(); public Composite(string name) : base(name) { } public override void Add(Component c) { chilidren.Add(c); } public override void Remove(Component c) { chilidren.Remove(c); } public override void Display(int depth) { Console.WriteLine(new String('-', depth) + name); foreach (Component component in chilidren) { component.Display(depth + 3); } } }}
program.cs

using System;using System.Collections.Generic;using System.Text;namespace Composite{ 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); Leaf leaf = new Leaf("Leaf D"); root.Add(leaf); root.Remove(leaf); root.Display(1); Console.Read(); } }}
运行结果:
-root
----Leaf A
----Leaf B
----Composite X
-------Leaf XA
-------Leaf XB
来源:https://www.cnblogs.com/wendy_soft2008/archive/2010/01/21/1653637.html