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

代码实现
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 );
}
}
//组合类
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 void Remove(Component c)
{
children.Remove(c);
}
//遍历子节点并展示
public override void Display(int depth)
{
Console.WriteLine(new string('-', depth) + name);
foreach (Component component in children)
{
component.Display(depth + 2);
}
}
}
client代码
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);
//同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);
//展示结果
root.Display(1);
Console.Read();
}
适用情况
1、需求中是体现部分与总体层次的结构时。
2、你希望用户能够忽略组合对象鱼单个对形象的不同。统一地使用组合结构中的全部对象时。
特点
以单一职责设计原则换取透明性,即通过让组件的接口同一时候包括一些管理子节点和叶节点的操作。客户能够将组合和叶节点一视同仁。
也就是说,一个元素到底是组合还是叶节点。对客户是透明的。
有时候系统须要遍历一个树枝构件的子构件多次,这时候能够遍历结果缓存起来。