Java的组合模式怎么实现
导读:本文共3265字符,通常情况下阅读需要11分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要: 1、什么是组合模式Compose objects into tree structures to represent part-whole hierarchies.Composite lets clients treat individual objects and compositions of objects uniformly.组合模式(Composite... ...
目录
(为您整理了一些要点),点击可以直达。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{//构件容器privateArrayList<Component>componentArrayList=newArrayList<>();//增加一个叶子节点或者树枝节点publicvoidadd(Componentcomponent){this.componentArrayList.add(component);}//删除一个叶子节点或者树枝节点publicvoidremove(Componentcomponent){this.componentArrayList.remove(component);}//获取分支下所有叶子节点和树枝节点publicList<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(Compositeroot){for(Componentc:root.getChildren()){if(cinstanceofLeaf){//叶子节点c.doSomething();}else{display((Composite)c);}}}}
这里我们在举一个例子:
假设我们在开发一个 OA 系统(办公自动化系统)。公司的组织结构包含部门和员工两种数据类型。其中,部门又可以包含子部门和员工。
我们希望在内存中构建整个公司的人员架构图(部门、子部门、员工的隶属关系),并且提供接口计算出部门的薪资成本(隶属于这个部门的所有员工的薪资和)。
/***部门类和员工类的抽象类*/publicabstractclassHumanResource{protectedlongid;protecteddoublesalary;publicHumanResource(longid){this.id=id;}publiclonggetId(){returnid;}publicabstractdoublecalculateSalary();}
publicclassDepartmentextendsHumanResource{privateList<HumanResource>subNodes=newArrayList<>();publicDepartment(longid){super(id);}@OverridepublicdoublecalculateSalary(){doubletotalSalary=0d;for(HumanResourcehr:subNodes){totalSalary+=hr.calculateSalary();}this.salary=totalSalary;returntotalSalary;}publicvoidaddSubNode(HumanResourcehumanResource){subNodes.add(humanResource);}}
publicclassEmployeeextendsHumanResource{publicEmployee(longid,doublesalary){super(id);this.salary=salary;}@OverridepublicdoublecalculateSalary(){returnsalary;}}
测试:
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(Departmentdepartment){//根据部门id查询数据库所有下属部门id//List<Long>subDepartmentIds=departmentRepo.getSubDepartmentIds(department.getId());List<Long>subDepartmentIds=newArrayList<>();for(LongsubDepartmentId:subDepartmentIds){DepartmentsubDepartment=newDepartment(subDepartmentId);department.addSubNode(subDepartment);buildOrganization(subDepartment);}//根据部门id查询数据库其关联员工所有id//List<Long>employeeIds=employeeRepo.getDepartmentEmployeeIds(department.getId());List<Long>employeeIds=newArrayList<>();for(LongemployeeId:employeeIds){//根据employeeId查询数据库得到salary//假设为1000doublesalary=1000d;department.addSubNode(newEmployee(employeeId,salary));}}}
4、组合模式优点
①、高层模块调用简单
一棵树形机构中的所有节点都是Component, 局部和整体对调用者来说没有任何区别,也就是说, 高层模块不必关心自己处理的是单个对象还是整个组合结构, 简化了高层模块的代码。
②、节点自由增加
使用了组合模式后, 如果想增加一个树枝节点、 叶子节点都很容易, 只要找到它的父节点就成, 非常容易扩展, 符合开闭原则, 对以后的维护非常有利。
5、组合模式应用场景
只要是树形结构,就可以考虑使用组合模式。
①、维护和展示部分-整体关系的场景, 如树形菜单、 文件和文件夹管理。
②、从一个整体中能够独立出部分模块或功能的场景。
</div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
Java的组合模式怎么实现的详细内容,希望对您有所帮助,信息来源于网络。