深入浅出组合模式
1 概念
基本概念:组合模式是结构型设计模式的一种,用来表示“整体-部分”的关系,使用户对单个对象和组合对象具有一致的访问性。
主要解决:将整体的各个部分都一视同仁,共同进行处理或操作,具有一致的行为,使得操作者与复杂的部分元素解耦合。
2 应用场景
- 树形菜单
- 目录、文件管理
- 部门-员工管理
- 整体与部分的场景
- …
3 代码实现
【场景说明】公司的工资结算系统需要计算出每位员工和每个部门的工资,使用组合模式实现一个程序,能够分别计算出每位员工的薪资和每个部门的工资总和
【类的设计】
【具体代码】
/** * @desc: 员工和部门共同部分(薪资)的抽象 * @author: YanMingXin * @create: 2021/9/25-21:31 **/ public abstract class SalaryTools { public Integer id; public Double salary; public abstract Double getThisSalary(); public SalaryTools(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Double getSalary() { return salary; } public void setSalary(Double salary) { this.salary = salary; } }
/** * @desc: 部门类 * @author: YanMingXin * @create: 2021/9/25-21:33 **/ public class Department extends SalaryTools { private List<SalaryTools> list = new ArrayList<>(); public Department(Integer id) { super(id); } @Override public Double getThisSalary() { double sum = 0; for (SalaryTools obj : list) { sum += obj.getThisSalary(); } this.salary = sum; return salary; } public void addDepartOrEmployee(SalaryTools obj) { this.list.add(obj); } public List<SalaryTools> getList() { return list; } }
/** * @desc: 员工类 * @author: YanMingXin * @create: 2021/9/25-21:32 **/ public class Employee extends SalaryTools { public Employee(Integer id, Double salary) { super(id); this.salary = salary; } @Override public Double getThisSalary() { return salary; } }
/** * @desc: 测试类 * @author: YanMingXin * @create: 2021/9/25-21:29 **/ public class MyComposite { public static void main(String[] args) { Department department = new Department(1001); Department dep1 = new Department(10011); Employee e1 = new Employee(10011, 10000D); Employee e2 = new Employee(100111, 10000D); Employee e3 = new Employee(100112, 10000D); department.addDepartOrEmployee(e1); dep1.addDepartOrEmployee(e2); dep1.addDepartOrEmployee(e3); department.addDepartOrEmployee(dep1); //System.out.println("001部门总工资:" + department.getThisSalary()); //System.out.println("0011部门总工资:" + dep1.getThisSalary()); List<SalaryTools> list = department.getList(); for (SalaryTools salaryTools : list) { if (salaryTools instanceof Department) { System.out.println("部门" + salaryTools.getId() + ":" + salaryTools.getThisSalary()); List<SalaryTools> list1 = ((Department) salaryTools).getList(); for (SalaryTools salaryTools1 : list1) { System.out.println("员工" + salaryTools1.getId() + ":" + salaryTools1.getThisSalary()); } } else { System.out.println("员工" + salaryTools.getId() + ":" + salaryTools.getThisSalary()); } } } }