组合模式也叫合成模式,有时又叫做部分-整体模式,主要是用来描述部分与整体的关系,其定义为:将对象组合成树形结构以表示“整体与部分”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。----设计模式之禅
个人理解
组合模式目的是将整体与部分组合成树形来表示整体与部分的层次,使得用户对单个对象和组合对象的使用具有一致性的接口,也就是通过接口对子对象统一操作。
案例
公司的结构往往属于树状结构,当我们需要打印整个公司的员工的信息的时候,切分成树叶和树枝的话会方便很多,但是打印每一个对象的时候,方法应该说是一致的,那么这种情况下使用组合模式,将整体与部分组合成树形来表示整体与部分的层次,使用户对单个对象和组合对象的使用具有一致性的接口。这样的话,在访问每一部分的时候,不需要单独的定义打印信息的方法了,通过统一的方法执行就可以了。
主要的代码如下
Corp类
public abstract class Corp {
// 姓名
private String name = "";
// 职位
private String position = "";
// 薪水
private int salary = 0;
public Corp(String name, String position, int salary){
this.name = name;
this.position = position;
this.salary = salary;
}
public String getInfo(){
return "姓名:" + this.name + "\t职位" + this.position + "\t薪水" + this.salary;
}
}
叶子节点Leaf
public class Leaf extends Corp {
public Leaf(String name, String position, int salary) {
super(name, position, salary);
}
}
树枝节点Branch
public class Branch extends Corp {
ArrayList<Corp> subList = new ArrayList<Corp>();
public Branch(String name, String position, int salary) {
super(name, position, salary);
}
public void addSubordinate(Corp corp){
this.subList.add(corp);
}
public ArrayList<Corp> getSubordinate(){
return this.subList;
}
}
public class Client {
public static void main(String[] args) {
Branch root = new Branch("wy", "root", 888888);
Branch it = new Branch("it1", "研发", 88888);
Branch market = new Branch("market1", "市场", 88888);
Leaf leaf_it = new Leaf("wangyang", "it", 8888);
Leaf leaf_it2 = new Leaf("wangy", "it", 8888);
Leaf leaf_market1 = new Leaf("wanan", "市场", 8888);
Leaf leaf_market2 = new Leaf("wany", "市场", 8888);
root.addSubordinate(it);
root.addSubordinate(market);
it.addSubordinate(leaf_it);
it.addSubordinate(leaf_it2);
market.addSubordinate(leaf_market1);
market.addSubordinate(leaf_market2);
String info = getTreeInfo(root);
System.out.println(root.getInfo());
System.out.println(info);
}
public static String getTreeInfo(Branch root){
ArrayList<Corp> subList = root.getSubordinate();
String info = "";
for (Corp corp : subList) {
if(corp instanceof Leaf){
info = info + corp.getInfo() + "\n";
}
else{
info = info + corp.getInfo() + "\n" + getTreeInfo((Branch)corp);
}
}
return info;
}
}
输出公司的员工工资等信息
组合模式优点
1. 高层模块调用简单,高层模块不必关心自己处理的是单个对象还是整个组合结构,简化了高层模块的代码。
2. 节点自由增加。只要找到他的父节点,增加树叶节点很容易,符合开闭原则(对扩展开放,对修改关闭)。
使用场景
1. 部分-整体关系的场景,比如树形结构、菜单、文件等。
2. 从一个整体中独立出来的部分模块和功能。
源码下载