一、组合模式的定义
Compose objects into tree structures to represent part-whole hierarchies.Compositelets clients treat individual objects and compositions of objects uniformly.(将对象组合成的树形结构以表示”部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。)
二、组合模式的应用
1、组合模式的优点
高层模块调用简单。一棵树形机构中的所有节点都是Component,局部和整体对调用者来说没有区别,也就是说,高层模块不必关心自己处理的是单个对象还是整个组合结构,简化了高层模块的代码。
节点自由增加。使用了组合模式后,我们可以看看,如果想增加一个树枝节点是不是都很容易,只要找到它的父节点就成,非常容易扩展,符合开闭原则,对以后的维护非常有利。
2、组合模式的缺点
组合模式又一个非常明显的缺点,直接使用实现类,这在面向接口编程上是很不恰当的,与依赖倒置原则冲突,使用时要考虑清楚,它限制了接口的影响范围。
3.组合模式的使用场景。
维护和展示部分-整体关系的场景,如树形菜单、文件和文件夹管理
从一个整体中能够独立出部分模块或功能的场景
三、组合模式的实现
//抽象构件
public abstract class Component {
private String name = "";
private String position = "";
private int salary = 0;
//通过构造函数传递信息
public Component(String _name, String _position, int _salary){
this.name = _name;
this.position = _position;
this.salary = _salary;
}
public String getInfo() {
String info = "";
info = "名称:" + this.name;
info = info + "\t职位:" + this.position;
info = info + "\t薪水:" + this.salary;
return info;
}
public abstract void add(Component component);
public abstract void remove(Component component);
public abstract ArrayList<Component> getChildren();
}
//叶子节点
public class Leaf extends Component {
public Leaf(String _name, String _position, int _salary) {
super(_name, _position, _salary);
}
@Deprecated
public void add(Component component) {
//空实现 直接抛出一个“不支持请求”异常
throw new UnsupportedOperationException();
}
@Deprecated
public void remove(Component component) {
//空实现 直接抛出一个“不支持请求”异常
throw new UnsupportedOperationException();
}
@Deprecated
public ArrayList<Component> getChildren() {
//空实现 直接抛出一个“不支持请求”异常
throw new UnsupportedOperationException();
}
}
//树枝节点
public class Branch extends Component {
//保存树枝节点下的子树枝节点和树叶节点,也就是高级下属和基础下属
private ArrayList subordinateList = new ArrayList();
public Branch(String _name, String _position, int _salary) {
super(_name, _position, _salary);
}
@Override
public void add(Component component) {
this.subordinateList.add(component);
}
@Override
public void remove(Component component) {
this.subordinateList.remove(component);
}
@Override
public ArrayList<Component> getChildren() {
return this.subordinateList;
}
}
//树枝节点
public class Branch extends Component {
//保存树枝节点下的子树枝节点和树叶节点,也就是高级下属和基础下属
private ArrayList subordinateList = new ArrayList();
public Branch(String _name, String _position, int _salary) {
super(_name, _position, _salary);
}
@Override
public void add(Component component) {
this.subordinateList.add(component);
}
@Override
public void remove(Component component) {
this.subordinateList.remove(component);
}
@Override
public ArrayList<Component> getChildren() {
return this.subordinateList;
}
}
四、 组合模式在源码中的应用
ViewGroup和View的结构就是一个组合模式