设计模式:组合模式(Composite)

时间:2023-03-09 20:27:20
设计模式:组合模式(Composite)

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

结构图:

设计模式:组合模式(Composite)

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("Cannot add a leaf");
} public override void Remove(Component c)
{
Console.WriteLine("Cannot remove from leaf");
} public override void Display(int depth)
{
Console.WriteLine(new string('-', depth) + name);
}
}

Composite类:

 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 + );
}
}
}

客户端调用:

Composite root = new Composite("root");
root.Add(new Leaf("LeafA"));
root.Add(new Leaf("LeafB")); Composite comp = new Composite("CompositeX");
comp.Add(new Leaf("LeafXA"));
comp.Add(new Leaf("LeafXB")); root.Add(comp); Composite comp2 = new Composite("CompositeY");
comp2.Add(new Leaf("LeafYA"));
comp2.Add(new Leaf("LeafYB")); comp.Add(comp2); root.Add(new Leaf("LeafC")); Leaf leaf = new Leaf("LeafD");
root.Add(leaf);
root.Remove(leaf); root.Display();

测试结果:
设计模式:组合模式(Composite)

何时使用组合模式?

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

示例:行政部和财务部可以看着是单个对象,北京分公司和上海分公司可以看成组合对象,而总公司是个更大的组合对象。

设计模式:组合模式(Composite)

组合对象好处:

基本对象可以被组合成更复杂的对象,而这个组合对象又可以被组合,这样不断地递归下去,客户端代码中,任何用到基本对象的地方都可以使用组合对象。

组合模式让客户可以一致的使用组合结构和单个对象。

参考:《大话设计模式》