个人博客:打开链接
一、定义
将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
二、通用类图
1:Component 抽象构件角色
定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性。
2:Leaf 叶子构件
叶子对象,其下再也没有其他的分支,也就是遍历的最小单位。
3:Composite 树枝构件
树枝对象,它的作用是组合树枝节点和叶子节点形成一个树形结构。
三、通用代码
1:抽象构件
public abstract class Component {
//个体和整体都具有的共享
public void doSomthing() {
System.out.println("Component doSomthing");
}
}
2:树枝构件
public class Composite extends Component {
//构件容器
private ArrayList<Component> components = new ArrayList<Component>();
//增加一个叶子构件或树枝构件
public void add(Component component) {
this.components.add(component);
}
//删除一个叶子构件或树枝构件
public void remove(Component component) {
this.components.remove(component);
}
//获取分支下的所有叶子构件和树枝构件
public ArrayList<Component> getChildren() {
return this.components;
}
}
3:叶子构件
public class Leaf extends Component {
//可以覆盖父类方法
/*
public void doSomething() {
}
*/
}
4:场景类
public class Client {
public static void main(String[] args) {
//创建一个根节点
Composite root = new Composite();
root.doSomthing();
//创建一个树枝构件
Composite branch = new Composite();
//创建一个叶子节点
Leaf leaf = new Leaf();
//建立整体
root.add(branch);
branch.add(leaf);
dispaly(root);
}
//通过递归遍历树
public static void dispaly(Composite root) {
for(Component c : root.getChildren()) {
if (c instanceof Leaf) {//叶子节点
c.doSomthing();
} else {//树枝节点
dispaly((Composite) c);
}
}
}
}
组合模式是对依赖倒转原则的破坏,但是它还有其他类型的变形。
四、优缺点
1:高层模块调用简单。一颗树形机构中的所有节点都是Component,局部和整体对调用者来说没有任何区别,也就是说,高层模块不必关心自己处理的是单个对象还是整体组合结构。
2:节点自由增加。
3:在场景类的定义中,树叶和树枝使用实现类定义,这与依赖倒置原则冲突,这样限制了接口的影响范围。
五、注意点
只要是树形结构,就要考虑使用组合模式,只要是要体现局部和整体的关系的时候,而且这种关系可能比较深,就考虑组合模式。