类图
定义
将对象组合成树形结构以表示部分 - 整体
的层次结构,使得用户对单个对象和组合对象的使用具有一致性
优点
- 高层模块调用简单 高层模块不必关心自己处理的是单个对象还是整个组合结构
- 节点自由增加缺点
- 场景类中,树枝和树叶使用时都需用起实现类,与依赖倒置原则冲突,没有面向接口编程
使用场景
- 维护和展示部分 - 整体关系的场景,如树形菜单,文件和文件夹管理
- 从一个整体中能够独立出部分模块或功能的场景
只要是树形结构就可以考虑使用组合模式
抽象构件
public abstract class Component {
/**
* 个体和整体都具有的共享
*/
public abstract void operation();
}
树枝构件
public class Composite extends Component {
private ArrayList<Component> componentArrayList = new ArrayList<>();
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;
}
@Override
public void operation() {
System.out.println("Composite->operation()");
}
}
树叶构件
public class Leaf extends Component {
private String name;
public Leaf(String name) {
System.out.println("新建树叶:" + name);
this.name = name;
}
@Override
public void operation() {
System.out.println("Leaf->" + name);
}
}
场景类
public class Client {
public static void main(String[] args) {
// 创建一个根节点
Composite root = new Composite();
root.operation();
/*
root
/ \
branch leaf3
/ \
leaf1 leaf2
*/
Composite branch = new Composite();
branch.add(new Leaf("leaf1"));
branch.add(new Leaf("leaf2"));
root.add(branch);
root.add(new Leaf("leaf3"));
display(root);
}
public static void display(Composite root) {
for (Component c : root.getChild()) {
if (c instanceof Leaf) {
c.operation();
} else {
display((Composite) c);
}
}
}
}
运行结果
Composite->operation()
新建树叶:leaf1
新建树叶:leaf2
新建树叶:leaf3
Leaf->leaf1
Leaf->leaf2
Leaf->leaf3