组合模式
将对象组合成树形结构以表示“部分-整体”的层次架构,使得用户对单个对象和组合对象的使用具有一致性。
组合模式角色
- 抽象构件(Component)角色:该角色定义了参加组合对象的共有方法和属性,规范一些默认的行为接口;
- 叶子构件(Leaf)角色:该角色是叶子对象,其下没有其他的分支,定义出参加组合的原始对象的行为;
- 树枝构件(Composite)角色:该角色代表参加组合的、其下有分支的树枝对象,它的作用是将树枝和叶子组合成一个树形结构,并定义出管理子对戏的方法。
组合模式的优点
- 高层模块调用简单。一棵树形结构的中的所有节点都是Component,局部和整体对调用者来说没有任何的区别,即高层模块不需要去关心自己处理的是单个对象还是整个组合结构,简化了高层模块的代码;
- 节点自由增加。使用组合模式后,如果想增加一个树枝节点、树叶节点只需要找到其父类节点即可。
使用场景
- 需要描述对象的部分和整体的等级结构,如文件和文件夹管理;
- 需要客户端忽略个体构件和组合构件的区别,平等对待所有的构件。
<span style="font-size:18px;">package compositedemo;
/**
* 定义抽象构件接口,定义参加组合对象的
* 共有方法和属性,规范一些默认的行为
*
*/
public interface Component {
public void operation();
}
</span>
<span style="font-size:18px;">package compositedemo;
/**
* 定义一个叶子几点构件,实现抽象构件方法
*
*/
public class Leaf implements Component {
@Override
public void operation() {
// TODO Auto-generated method stub
System.out.println("我是叶子节点");
}
}
</span>
<span style="font-size:18px;">package compositedemo;
import java.util.ArrayList;
import java.util.List;
/**
* 定义树枝构件
*
*/
public class Composite implements Component {
//构件容器,该树枝构件下所拥有的树枝构件或叶子构件
private List<Component> componentList = new ArrayList<Component>();
//添加构件
public void add(Component component){
componentList.add(component);
}
//删除构件
public void remove(Component component){
componentList.remove(component);
}
//获取子构件
public List<Component> getCldList(){
return this.componentList;
}
//树枝构件属于抽象构件,也有自己的operation方法
public void operation() {
// TODO Auto-generated method stub
System.out.println("我是树枝");
}
}
</span>
<span style="font-size:18px;">package compositedemo;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建一个根节点
Composite root = new Composite();
root.operation();
//创建树枝节点
Composite branch = new Composite();
//创建叶子节点
Component leaf = new Leaf();
//构件树形结构
branch.add(leaf);
root.add(branch);
display(root);
}
//遍历数
public static void display(Composite root){
for(Component c : root.getCldList()){
if(c instanceof Leaf){//叶子节点
c.operation();//叶子节点,不需要再遍历
}else{
c.operation();
display((Composite)c);//继续遍历数
}
}
}
}
</span>