概念:将对象组合成树形结构以表示“部分——整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性
核心:需求中是提现部分与整体层次的结构时,整体与部分可以一致对待。
操作树关系图

组合模式结构图

image.png

java代码:

  1. public class CompositeTest {
  2. public static void main(String[] args) {
  3. Component root = new Composite("根节点");
  4. Component leaf1 = new Leaf("根节点叶子节点1");
  5. Component leaf2 = new Leaf("根节点叶子节点2");
  6. root.Add(leaf1);
  7. root.Add(leaf2);
  8. Component composite = new Composite("根节点组合节点1");
  9. root.Add(composite);
  10. Component leaf3 = new Leaf("根节点叶子节点3");
  11. Component leaf4 = new Leaf("根节点叶子节点4");
  12. composite.Add(leaf3);
  13. composite.Add(leaf4);
  14. root.Display(0);
  15. }
  16. }
  17. //叶子节点和叶节点的抽象类
  18. public abstract class Component {
  19. String name;
  20. public Component(String name) {
  21. this.name = name;
  22. }
  23. public String getName() {
  24. return name;
  25. }
  26. public void setName(String name) {
  27. this.name = name;
  28. }
  29. public abstract void Add(Component component);
  30. public abstract void Remove(Component component);
  31. public abstract void Display(int depth);
  32. }
  33. //叶节点
  34. public class Composite extends Component {
  35. List<Component> list = new ArrayList<>();
  36. public Composite(String name) {
  37. super(name);
  38. }
  39. @Override
  40. public void Add(Component component) {
  41. list.add(component);
  42. }
  43. @Override
  44. public void Remove(Component component) {
  45. list.remove(component);
  46. }
  47. @Override
  48. public void Display(int depth) {
  49. for (int i = 0 ; i <= depth ; i ++){
  50. System.out.print("-");
  51. }
  52. System.out.println(name);
  53. for (Component component : list) {
  54. component.Display(depth + 2);
  55. }
  56. }
  57. }
  58. //叶子节点
  59. public class Leaf extends Component {
  60. public Leaf(String name) {
  61. super(name);
  62. }
  63. @Override
  64. public void Add(Component component) {
  65. System.out.println("can not add by leaf");
  66. }
  67. @Override
  68. public void Remove(Component component) {
  69. System.out.println("can not remove by leaf");
  70. }
  71. @Override
  72. public void Display(int depth) {
  73. for (int i = 0 ; i <= depth ; i ++){
  74. System.out.print("-");
  75. }
  76. System.out.println(name);
  77. }
  78. }