相信树形结构大家都知道,但是你是否知道用到了什么设计模式吗?
1、什么是组合模式?
Compose objects into tree structures to represent part-whole hierarchies.Composite lets clients treat individual objects and compositions of objects uniformly.
组合模式(Composite Pattern):将对象组合成树形结构以表示“部分-整体”的层次结构, 使得用户对单个对象和组合对象的使用具有一致性。
说人话:用于处理树形结构数据。
2、组合模式定义

①、Component 抽象构件角色
定义参加组合对象的共有方法和属性,可以定义一些默认的行为或属性。
②、Leaf 叶子节点
叶子对象,其下再也没有其他的子节点,是遍历的最小单位。
③、Composite 树枝构件
树枝对象,作用是组合树枝节点和叶子节点形成一个树形结构。
3、组合模式通用代码实现
/**
* 个体和整体的抽象
*/publicabstractclassComponent {
// 个体和整体都有的共享publicvoiddoSomething(){
// 通用业务逻辑
System.out.println("通用业务逻辑");
}
复制代码
/**
* 树枝节点
*/publicclassCompositeextendsComponent{
// 构件容器private ArrayList<Component> componentArrayList = newArrayList<>();
// 增加一个叶子节点或者树枝节点publicvoidadd(Component component){
this.componentArrayList.add(component);
}
// 删除一个叶子节点或者树枝节点publicvoidremove(Component component){
this.componentArrayList.remove(component);
}
// 获取分支下所有叶子节点和树枝节点public List<Component> getChildren(){
returnthis.componentArrayList;
}
}
复制代码
/**
* 叶子节点
*/publicclassLeafextendsComponent {
// 覆写父类方法@OverridepublicvoiddoSomething() {
// 叶子节点逻辑
System.out.println("叶子节点逻辑");
}
}
复制代码
测试:
publicclassClientTest {
publicstaticvoidmain(String[] args) {
// 创建一个根节点Compositeroot=newComposite();
root.doSomething();
// 创建一个树枝构件Compositebranch=newComposite();
// 创建一个叶子节点Leafleaf=newLeaf();
// 串联起来
root.add(branch);
branch.add(leaf);
display(root);
}
// 通过递归遍历数publicstaticvoiddisplay(Composite root){
for(Component c : root.getChildren()){
if(c instanceof Leaf){ // 叶子节点
c.doSomething();
}else{
display((Composite) c);
}
}
}
}
复制代码
这里我们在举一个例子:
假设我们在开发一个 OA 系统(办公自动化系统)。公司的组织结构包含部门和员工两种数据类型。其中,部门又可以包含子部门和员工。
我们希望在内存中构建整个公司的人员架构图(部门、子部门、员工的隶属关系),并且提供接口计算出部门的薪资成本(隶属于这个部门的所有员工的薪资和)。

/**
* 部门类和员工类的抽象类
*/publicabstractclassHumanResource {
protectedlong id;
protecteddouble salary;
publicHumanResource(long id){
this.id = id;
}
publiclonggetId(){
return id;
}
publicabstractdoublecalculateSalary();
}
复制代码
publicclassDepartmentextendsHumanResource{
private List<HumanResource> subNodes = newArrayList<>();
publicDepartment(long id){
super(id);
}
@OverridepublicdoublecalculateSalary() {
doubletotalSalary=0d;
for (HumanResource hr : subNodes){
totalSalary += hr.calculateSalary();
}
this.salary = totalSalary;
return totalSalary;
}
publicvoidaddSubNode(HumanResource humanResource){
subNodes.add(humanResource);
}
}
复制代码
publicclassEmployeeextendsHumanResource{
publicEmployee(long id,double salary){
super(id);
this.salary = salary;
}
@OverridepublicdoublecalculateSalary() {
return salary;
}
}
复制代码
测试:
publicclassPersonClientTest {
privatestaticfinallongORGANIZATION_ROOT_ID=1;
publicstaticvoidmain(String[] args) {
// 创建总部门Departmentroot=newDepartment(ORGANIZATION_ROOT_ID);
// 创建子部门Departmentbranch=newDepartment(2L);
// 创建员工Employeeemployee1=newEmployee(21L,2000);
Employeeemployee2=newEmployee(22L,4000);
root.addSubNode(branch);
branch.addSubNode(employee1);
branch.addSubNode(employee2);
doublev= root.calculateSalary();
System.out.println(v);
}
privatevoidbuildOrganization(Department department){
// 根据 部门id 查询数据库 所有下属部门 id// List<Long> subDepartmentIds = departmentRepo.getSubDepartmentIds(department.getId());
List<Long> subDepartmentIds = newArrayList<>();
for (Long subDepartmentId : subDepartmentIds){
DepartmentsubDepartment=newDepartment(subDepartmentId);
department.addSubNode(subDepartment);
buildOrganization(subDepartment);
}
// 根据部门id 查询数据库 其关联员工所有 id// List<Long> employeeIds = employeeRepo.getDepartmentEmployeeIds(department.getId());
List<Long> employeeIds = newArrayList<>();
for (Long employeeId : employeeIds){
// 根据 employeeId 查询数据库得到 salary// 假设为 1000doublesalary=1000d;
department.addSubNode(newEmployee(employeeId,salary));
}
}
}
复制代码
4、组合模式优点
①、高层模块调用简单
一棵树形机构中的所有节点都是Component, 局部和整体对调用者来说没有任何区别,也就是说, 高层模块不必关心自己处理的是单个对象还是整个组合结构, 简化了高层模块的代码。
②、节点自由增加
使用了组合模式后, 如果想增加一个树枝节点、 叶子节点都很容易, 只要找到它的父节点就成, 非常容易扩展, 符合开闭原则, 对以后的维护非常有利。
5、组合模式应用场景
只要是树形结构,就可以考虑使用组合模式。
①、维护和展示部分-整体关系的场景, 如树形菜单、 文件和文件夹管理。
②、从一个整体中能够独立出部分模块或功能的场景。
作者:初念初恋