前言
- 组合模式:部分和整体的模式,结构型设计模式之一.他将一组相似的对象看做一个对象处理,并根据一个树状结构来组合对象.
- 在android开发过程中,使用得并不多,更适用于对一些界面UI的架构设计上,
- 组合模式和解释器模式有一定的类同,两者在迭代对象时都涉及递归的调用.
定义
- 定义:将对象组合成属性结构以表示”部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性.
- 使用场景:表示对象的部分-整体层次结构,从一个整体能独立出部分模块或功能的场景.
UML类图
- component:抽象根节点,为组合中的类,申明接口对象
/**
* 抽象根节点
* @author max
*
*/
public abstract class Component {
public String name;
public Component(String name) {
super();
this.name = name;
}
public abstract void doSomething();
}
- composite:在component接口中实现与子节点有关的操作.
/**
* 具体枝干节点
* @author max
*
*/
public class Composite extends Component{
/**
* 存储节点的容器
*/
private List<Component> components = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void doSomething() {
}
/**
* 添加子节点
* @param component
*/
public void addChild(Component component){
components.add(component);
}
/**
* 移除子节点
* @param component
*/
public void removeChild(Component component){
components.remove(component);
}
public Component getChildren(int index){
return components.get(index);
}
}
/**
* 具体叶子节点
* @author max
*
*/
public class Leaf extends Component{
public Leaf(String name) {
super(name);
}
@Override
public void doSomething() {
}
}
- client:通过component操作组合节点的对象
/**
* 客户端调用
* @author max
*
*/
public class Client {
public static void main(String[] args){
Composite root = new Composite("haha");
Composite branch1 = new Composite("branch1");
Composite branch2 = new Composite("branch2");
Leaf leaf1 = new Leaf("leaf1");
Leaf leaf2 = new Leaf("leaf2");
branch1.addChild(leaf1);
branch2.addChild(leaf2);
root.addChild(branch1);
root.addChild(branch2);
root.doSomething();
}
}
总结
- 其实组合模式,就是感觉是父类去遍历子类调用递归方法,分别实现各抽象方法.
源码下载