组合模式定义:有时又叫作部分-整体模式,它是一种将对象组合成树状的层次结构的模式,用来表示“部分-整体”的关系,使用户对单个对象和组合对象具有一致的访问性。
主要意图:将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
主要解决:它在我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以像处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦。
优点:
1,组合模式使得客户端代码可以一致地处理单个对象和组合对象,无须关心自己处理的是单个对象,还是组合对象,这简化了客户端代码。
2,更容易在组合体内加入新的对象,客户端不会因为加入了新的对象而更改源代码,满足“开闭原则”。
缺点:
1,设计较复杂,客户端需要花更多时间理清类之间的层次关系。
2,不容易限制容器中的构件。
3,不容易用继承的方法来增加构件的新功能。
组合模式类图:
代码实现:
客户端代码:
using System;
namespace _01组合模式_基本构架
{
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);
Composite comp2 = new Composite("Composite XY");
comp2.Add(new Leaf("Leaf XYA"));
comp2.Add(new Leaf("Leaf XYB"));
comp.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();
}
}
}
组合中的对象:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace _01组合模式_基本构架
{
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);
}
}
合成:
using System;
using System.Collections.Generic;
using System.Text;
namespace _01组合模式_基本构架
{
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 componet in children)
{
componet.Display(depth+2);
}
}
}
}
节点:
using System;
using System.Collections.Generic;
using System.Text;
namespace _01组合模式_基本构架
{
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);
}
}
}
总结:客户端代码,很容易组建层次结构,并且层次分明,同时又很容易遍历所有的组件集合。但要注意理解组合模式中的节点与页,节点可删可加,页则不能增删。