您的位置:首页 > 其它

浅谈设计模式之组合模式

2016-05-26 14:27 218 查看
组合模式(Composite):将对象组合成树形结构以表示“部分—整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。

这个模式可以按照“部分—整体”来理解,组合就是部分组合成整体。就好比学院与学校的关系,学院里有食堂、寝室、教学楼,学校里当然也有,而学院是属于学校的一部分。也就是这里它们有一些共性可以提取出来。

UML图如下:



//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 :Componet
{
public Leaf(string name):base(name) {}
//其实叶子节点不应该实现这些东西,因为不会有分支了
public override void Add(Component c){
Print("Add a leaf");
}
//Remove Display略
}

//Composite定义有枝节点的行为,用来存储子部件
class Composite :Componet
{
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){
foreach(Component c in children){
c.DisPlay(depth + 2);
}
}
}

//测试
string void Main(string[] args)
{
Composite root = new Composite("root");
//叶子
root.Add(new Leaf("Leaf A"));
root.Add(new Leaf("Leaf B"));
//分支1
Composite comp1 = new Composite("Composite X");
comp1.Add(new Leaf("Leaf XA"));
comp1.Add(new Leaf("Leaf XB"));
root.Add(comp1);
//分支2
Composite comp2 = new Composite("Composite XY");
comp2.Add(new Leaf("Leaf XYA"));
comp2.Add(new Leaf("Leaf XYB"));
comp1.Add(comp2);

root.Add(new Leaf("Leaf C"));
//显示大树 类似深度优先
root.Display(1);
}


组合模式的分类

1) 安全方式: 将管理子元素的方法定义在Composite类中,但这样客户端需要作出相应判断节点类型

2) 透明方式:将管理子元素的方法定义在Component接口中,这样Leaf类就需要对这些方法空实现

这个模式经常和装饰模式相结合,并且二者通常共用父类。

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

参考书籍:《大话设计模式》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式