属于结构型模式(共7种)

    目的:
    树状结构专用模式

    类图
    image.png
    举例

    1. abstract class Node {
    2. abstract public void p();
    3. }
    4. class LeafNode extends Node {
    5. String content;
    6. public LeafNode(String content) {this.content = content;}
    7. @Override
    8. public void p() {
    9. System.out.println(content);
    10. }
    11. }
    12. class BranchNode extends Node {
    13. List<Node> nodes = new ArrayList<>();
    14. String name;
    15. public BranchNode(String name) {this.name = name;}
    16. @Override
    17. public void p() {
    18. System.out.println(name);
    19. }
    20. public void add(Node n) {
    21. nodes.add(n);
    22. }
    23. }
    24. public class Main {
    25. public static void main(String[] args) {
    26. BranchNode root = new BranchNode("root");
    27. BranchNode chapter1 = new BranchNode("chapter1");
    28. BranchNode chapter2 = new BranchNode("chapter2");
    29. Node r1 = new LeafNode("r1");
    30. Node c11 = new LeafNode("c11");
    31. Node c12 = new LeafNode("c12");
    32. BranchNode b21 = new BranchNode("section21");
    33. Node c211 = new LeafNode("c211");
    34. Node c212 = new LeafNode("c212");
    35. root.add(chapter1);
    36. root.add(chapter2);
    37. root.add(r1);
    38. chapter1.add(c11);
    39. chapter1.add(c12);
    40. chapter2.add(b21);
    41. b21.add(c211);
    42. b21.add(c212);
    43. tree(root, 0);
    44. }
    45. static void tree(Node b, int depth) {
    46. for(int i=0; i<depth; i++) System.out.print("--");
    47. b.p();
    48. if(b instanceof BranchNode) {
    49. for (Node n : ((BranchNode)b).nodes) {
    50. tree(n, depth + 1);
    51. }
    52. }
    53. }
    54. }