什么是组合模式?

组合模式又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。
简单说就是:用树结构组织对象,把多个对象当成一个对象使用。

适用场景

可以用树结构表示的业务场景,比如所有的组织结构,行政区划等等

代码实现

示例:一个公司的组织结构就是Tree结构,用组合模式展示

  1. //示例:公司的组织架构
  2. /**
  3. * 员工类
  4. */
  5. class Employee {
  6. private String name;
  7. private String dept;
  8. private int salary;
  9. private List<Employee> subordinates;
  10. //构造函数
  11. public Employee(String name, String dept, int sal) {
  12. this.name = name;
  13. this.dept = dept;
  14. this.salary = sal;
  15. subordinates = new ArrayList<Employee>();
  16. }
  17. public void add(Employee e) {
  18. subordinates.add(e);
  19. }
  20. public void remove(Employee e) {
  21. subordinates.remove(e);
  22. }
  23. public List<Employee> getSubordinates() {
  24. return subordinates;
  25. }
  26. @Override
  27. public String toString() {
  28. return ("Employee :[ Name : " + name
  29. + ", dept : " + dept + ", salary :"
  30. + salary + " ]");
  31. }
  32. }
  33. /**
  34. * 组合模式测试
  35. */
  36. public class CompositePattern {
  37. public static void main(String[] args) {
  38. Employee ceo = new Employee("John", "CEO", 30000);
  39. Employee headSales = new Employee("Robert", "Head Sales", 20000);
  40. Employee headMarketing = new Employee("Michel", "Head Marketing", 20000);
  41. Employee clerk1 = new Employee("Laura", "Marketing", 10000);
  42. Employee clerk2 = new Employee("Bob", "Marketing", 10000);
  43. Employee salesExecutive1 = new Employee("Richard", "Sales", 10000);
  44. Employee salesExecutive2 = new Employee("Rob", "Sales", 10000);
  45. ceo.add(headSales);
  46. ceo.add(headMarketing);
  47. headSales.add(salesExecutive1);
  48. headSales.add(salesExecutive2);
  49. headMarketing.add(clerk1);
  50. headMarketing.add(clerk2);
  51. //打印该组织的所有员工
  52. System.out.println(ceo);
  53. for (Employee headEmployee : ceo.getSubordinates()) {
  54. System.out.println(headEmployee);
  55. for (Employee employee : headEmployee.getSubordinates()) {
  56. System.out.println(employee);
  57. }
  58. }
  59. //输出:
  60. //Employee :[ Name : John, dept : CEO, salary :30000 ]
  61. //Employee :[ Name : Robert, dept : Head Sales, salary :20000 ]
  62. //Employee :[ Name : Richard, dept : Sales, salary :10000 ]
  63. //Employee :[ Name : Rob, dept : Sales, salary :10000 ]
  64. //Employee :[ Name : Michel, dept : Head Marketing, salary :20000 ]
  65. //Employee :[ Name : Laura, dept : Marketing, salary :10000 ]
  66. //Employee :[ Name : Bob, dept : Marketing, salary :10000 ]
  67. }
  68. }