设计模式目录
http://blog.csdn.net/fenglailea/article/details/52733435
风.fox
组合模式
将对象组合成树形结构表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性
通用类图
组成
- 抽象构件角色 Component
定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性 - 叶子构件 Leaf
叶子对象,其下再也没有其他的分支,也就是遍历的最小单位
- 树枝构件 Composite
树枝对象,他的作用是组合树枝节点和叶子节点形成一个树形结构
- 树枝构件 Composite
通用源码
JAVA
//抽象构件
public abstract class Component{
// 个体和整体都具有的共享
public void doSomething(){
...
}
}
// 树枝构件
public class Composite extends Component{
// 构件容器
private ArrayList<Component> componentArrayList= new ArrayList<Component>();
// 增加一个叶子构件或树枝构件
public void add(Component component){
this.componentArrayList.add(component);
}
//删除一个叶子构件或树枝构件
public void remove(Component component){
this.componentArrayList.remove(component);
}
//获得分支下的所有叶子构件和树枝构件
public ArrayList<Component> getChildred(){
return this.componentArrayList;
}
}
// 树叶构件
public class Leaf extends Component{
/**
* 可以覆写父类方法
* pulic void doSomething(){}
*/
}
//场景
public class Client{
public static void main(String[] args){
//创建一个节点
Composite root =new Composite();
root.doSomething();
//创建一个树枝构件
Composite branch=new Composite();
//创建一个叶子节点
Leaf leaf =new Leaf();
//建立整体
root.add(branch);
branch.add(leaf);
}
}
优点
高层模块调用简单
节点自有增加
使用场景
维护和展示部分-整体关系的场景
从一个整体中能够独立出部分模块或功能的场景