设计模式--组合模式

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

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

//定义一个组件的基类

abstract class Component
{
protected string name;

public Component(string name) { this.name = name; }
//Add和Remove方法来提供增加或移除树叶或树枝的功能
public abstract void Add(Component c);
public abstract void Remove(Component c);
public abstract void Display(int depth);
}

//实现

class Composite : Component
{
//一个子对象集合用来存储其下属的枝节点和叶节点
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 item in children)
{
item.Display(depth + 2);
}
}

}

class Leaf : Component
{
public Leaf(string name) : base(name)
{
}
//由于叶子没有再增加分枝和树叶。所以Add和Remove方法实现它没有意义,但这样做可以消除叶节点和枝节点对象在抽象层次的区别,它们具备完全一致的接口。
public override void Add(Component c)
{
Console.WriteLine("Cannot add to a leaf");
}

public override void Display(int depth)
{
Console.WriteLine(new string('-', depth) + name);
}

public override void Remove(Component c)
{
Console.WriteLine("Cannot remove from a leaf");
}
}

调用:

Composite root = new Composite("root");
root.Add(new Leaf("Leaf A"));
root.Add(new Leaf("Leaf B"));

Composite com = new Composite("Composite X");
com.Add(new Leaf("Leaf XA"));
com.Add(new Leaf("Leaf XB"));

root.Add(com);

Composite com2 = new Composite("Composite XY");
com2.Add(new Leaf("Leaf XYA"));
com2.Add(new Leaf("Leaf XYB"));
com.Add(com2);
root.Add(new Leaf("Leaf C"));

Leaf leaf = new Leaf("Leaf D");
root.Add(leaf);
//root.Remove(leaf);

root.Display(0);

原文地址:https://www.cnblogs.com/buzhidaojiaoshenme/p/6731424.html