您的位置:首页 > 其它

十五 设计模式之组合模式

2011-01-25 09:15 253 查看
定义



将对象组合成树形结构以表示“部分

-

整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性

类图







通用代码


//抽象构件
public abstract class Component {
//个体和整体都具有的共享
public void operation(){
//doSomething
}
}
//树枝构件
public class Composite extends Component {
private ArrayList<Component> componentArrayList = new ArrayList<Component>();
public void Add(Component param) {
this.componentArrayList.add(param);
}
public void Remove(Component param) {
this.componentArrayList.remove(param);
}
public  ArrayList<Component> GetChild() {
return this.componentArrayList;
}
}
//树叶构件
public class Leaf extends Component {
}
//场景类
public class Client {
public static void main(String args[]){
//创建一个根节点
Composite root = new Composite();
root.operation();
Composite branch = new Composite();
Leaf leaf = new Leaf();
root.Add(branch);
root.Add(leaf);
}
public static void display(Composite root){
for(Component c:root.GetChild()){
if(c instanceof Leaf){
c.operation();
}else{
display((Composite)c);
}
}
}
}




优点


1.


高层模块调用简单

高层模块不必关心自己处理的是单个对象还是整个组合结构

2.


节点自由增加

缺点


场景类中,树枝和树叶使用时都需用起实现类,与依赖倒置原则冲突,没有面向接口编程

使用场景


1.


维护和展示部分
-
整体关系的场景,如树形菜单,文件和文件夹管理

2.


从一个整体中能够独立出部分模块或功能的场景

只要是树形结构就可以考虑使用组合模式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: