组合模式
组合模式的几个角色:
- Component 抽象构建角色。 定义参加组合对象的共有方法 和属性。
- Leaf叶子构件。 叶子对象,其下没有其他的分支。
- Composite 树枝构件。 树枝对象,他的作用是组合树枝节点和叶子节点形成一个树形结构。
public abstract class Component {
public void doSomething(){
}
}
public class Composite extends Component{
private ArrayList<Component> componentArrayList=new ArrayList<>();
public void add(Component component){
this.componentArrayList.add(component);
}
public void remove(Component component){
this.componentArrayList.remove(component);
}
public ArrayList<Component> getChildren(){
return this.componentArrayList;
}
}
public class Leaf extends Component{
@Override
public void doSomething(){
System.out.println("leaf node");
}
}
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);
}
public static void display(Composite root){
for(Composite c:root.getChildren()){
if(c instanceof Leaf){
((Leaf) c).doSomething();
}else{
display(c);
}
}
}
}
组合模式的优点
- 高层模块调用简单。 所有的树形结构中的节点就是Component, 高层模块不必关心自己处理的是单个对象还是组合结构,简化了高层模块的代码。
- 节点自由增加。容易扩展
组合模式的缺点
- 直接使用了实现类。与依赖倒置,面向接口编程冲突。
组合模式的场景
- 维护和展示部分–整体关系的场景,如树形菜单,文件和文件夹管理。
- 从一个整体中能独立出部分模块和功能场景。
组合模式注意事项
只要是树形结构,就要考虑组合模式。 只要是呈现局部和整体的关系的时候,且这种关系比较深,考虑一下组合模式。