组合模式- 2020-12-02 22:54- 设计模式


组合模式 一般用于处理树型结构

demo

  1. /**
  2. * 节点
  3. *
  4. * @author Bai
  5. * @date 2020/12/2 22:30
  6. */
  7. @Data
  8. public class Node {
  9. /**
  10. * 节点名称
  11. */
  12. private String name;
  13. public Node(String name) {
  14. this.name = name;
  15. }
  16. }
  1. /**
  2. * @author Bai
  3. * @date 2020/12/2 22:31
  4. */
  5. public class BranchNode extends Node {
  6. public BranchNode(String name) {
  7. super(name);
  8. }
  9. /**
  10. * 子节点
  11. */
  12. private List<Node> childNodes = new ArrayList<>();
  13. public BranchNode add(Node node) {
  14. childNodes.add(node);
  15. return this;
  16. }
  17. public List<Node> getChildNodes() {
  18. return childNodes;
  19. }
  20. public void setChildNodes(List<Node> childNodes) {
  21. this.childNodes = childNodes;
  22. }
  23. }
  1. @Test
  2. public void demo() {
  3. //模拟一次 目录路径, 并且打印出 从根目录到子目录的 所有路径
  4. //根节点
  5. BranchNode root = new BranchNode("root");
  6. //根节点下有两个子级目录 chapter1 chapter2
  7. BranchNode chapter1 = new BranchNode("chapter1");
  8. //chapter1 下有两个子级目录
  9. BranchNode chapter1_1 = new BranchNode("chapter1_1");
  10. //chapter1_1下有一个子级
  11. Node chapter1_1_1 = new Node("chapter1_1_1");
  12. chapter1_1.add(chapter1_1_1);
  13. //chapter1_2为叶子目录
  14. Node chapter1_2 = new Node("chapter1_2");
  15. chapter1.add(chapter1_1).add(chapter1_2);
  16. //chapter2 下有三个子级目录
  17. BranchNode chapter2 = new BranchNode("chapter2");
  18. //chapter2 下有两个子级目录
  19. BranchNode chapter2_1 = new BranchNode("chapter2_1");
  20. //chapter2_1 下有一个子级
  21. Node chapter2_1_1 = new Node("chapter2_1_1");
  22. chapter2_1.add(chapter2_1_1);
  23. //chapter1_2为叶子目录
  24. Node chapter2_2 = new Node("chapter1_2");
  25. Node chapter2_3 = new Node("chapter2_3");
  26. chapter2.add(chapter2_1).add(chapter2_2).add(chapter2_3);
  27. root.add(chapter1);
  28. root.add(chapter2);
  29. //递归打印出来每个节点
  30. print(root, 0);
  31. }
  32. private void print(Node root, int depth) {
  33. for (int i = 0; i < depth; i++) {
  34. System.out.print("——");
  35. }
  36. System.out.println(root.getName());
  37. if (root instanceof BranchNode) {
  38. BranchNode branchNode = (BranchNode) root;
  39. for (Node childNode : branchNode.getChildNodes()) {
  40. print(childNode, depth + 1);
  41. }
  42. }
  43. }

**

  1. root
  2. ——chapter1
  3. ————chapter1_1
  4. ——————chapter1_1_1
  5. ————chapter1_2
  6. ——chapter2
  7. ————chapter2_1
  8. ——————chapter2_1_1
  9. ————chapter1_2
  10. ————chapter2_3

**