简介
组合模式又叫整体-部分模式,它允许你将对象组合成树形结构来表现整体-部分层次结构,让使用者可以以一致的方式处理组合对象以及部分对象
角色
(1)抽象构件(Component)角色: 定义了叶子和容器构件的共同点
(2)叶子(Leaf)构件角色:无子节点
(3)容器(Composite)构件角色: 有容器特征,可以包含子节点
使用场景
- 只要是树形结构或者只要是要体现局部和整体的关系的时候,而且这种关系还可能比较深,就要考虑一下组合模式。
- 从一个整体中能够独立出部分模块或功能的场景。
- 维护和展示部分-整体关系的场景。
代码示例
已常见的组织架构为例子
安全模式
抽象构建类
//抽象构建
public abstract class Component {
String getName() {
return null;
}
//个体和整体都具有
void print(){
}
}
部门类
public class Composite extends Component{
private String name;
public Composite(String name){
this.name = name;
}
//构件容器
private List<Component> componentArrayList = new ArrayList<Component>();
@Override
public String getName() {
return this.name;
}
public void add(Component component){
componentArrayList.add(component);
}
public void remove(Component component){
componentArrayList.remove(component);
}
@Override
public void print() {
System.out.println(this.getName());
for (Component component : this.componentArrayList) {
component.print();
}
}
}
人员类
public class Leaf extends Component {
private String name;
public Leaf(String name){
this.name = name;
}
@Override
String getName() {
return this.name;
}
@Override
void print() {
System.out.println(this.name);
}
}
演示
public class Demo {
public static void main(String[] args) {
Composite composite = new Composite("一级部门");
Leaf boss = new Leaf("老板");
composite.add(boss);
Composite composite2 = new Composite("二级部门");
composite.add(composite2);
Leaf zs = new Leaf("张三");
Leaf ls = new Leaf("李四");
composite2.add(zs);
composite2.add(ls);
composite.print();
}
}
结果
透明模式
刚刚的安全模式中抽象构建只存放了公有的方法,容器中也就是部门里实现了部门自己的add和remove方法,透明模式呢就是将add和remove也抽象到抽象构建当中
//抽象构建
public abstract class Component {
String getName() {
return null;
}
//个体和整体都具有
void print(){
}
public void add(Component component){
}
public void remove(Component component){
}
}
安全模式和透明模式的区别
- 安全模式在抽象组件中只定义一些默认的行为或属性,它是把树枝节点和树叶节点彻底分开;透明模式是把用来组合使用的方法放到抽象类中,不管叶子对象还是树枝对象都有相同的结构,通过判断确认是叶子节点还是树枝节点,如果处理不当,这个会在运行期出现问题,不是很建议的方式。
- 安全模式与依赖倒置原则冲突;透明模式的好处就是它基本遵循了依赖倒转原则,方便系统进行扩展。
- 安全模式在遍历树形结构的的时候需要进行强制类型转换;在透明模式下,遍历整个树形结构是比较容易的,不用进行强制类型转换。