树状结构专用模式,一对多中,又可以嵌套一对多
(文件夹、文件)

代码结构
Java设计模式:组合模式_java
源码

package com.myspringboot.shejimoshi.zuhe;

import java.util.ArrayList;
import java.util.List;

public class BranchNode extends Node {
    List<Node> nodes = new ArrayList<Node>();

    public BranchNode(String name) {
        this.name = name;
    }

    @Override
    public void out() {
        System.out.println(name);
    }

    public void add(Node node) {
        nodes.add(node);
    }
}
package com.myspringboot.shejimoshi.zuhe;

public class LeafNode extends Node {

    public LeafNode(String name) {
        this.name = name;
    }

    @Override
    public void out() {
        System.out.println(name);
    }
}
package com.myspringboot.shejimoshi.zuhe;

import java.util.List;

public class Main {
    public static void main(String[] args) {
        BranchNode root = new BranchNode("root");
        BranchNode chapter1 = new BranchNode("chapter1");
        BranchNode chapter2 = new BranchNode("chapter2");
        Node r1 = new LeafNode("r1");
        Node c11 = new LeafNode("c11");
        Node c12 = new LeafNode("c12");
        BranchNode b21 = new BranchNode("section21");
        Node c211 = new LeafNode("c211");
        Node c212 = new LeafNode("c212");

        root.add(chapter1);
        root.add(chapter2);
        root.add(r1);
        chapter1.add(c11);
        chapter1.add(c12);
        chapter2.add(b21);
        b21.add(c211);
        b21.add(c212);

        tree(root, 0);

    }

    private static void tree(Node node, int depth) {
        for (int i = 0; i < depth; i++) {
            System.out.print("--");
        }
        node.out();

        if (node instanceof BranchNode) {
            List<Node> nodes = ((BranchNode) node).nodes;
            for (Node n : nodes) {
                tree(n, depth + 1);
            }
        }
    }
}
package com.myspringboot.shejimoshi.zuhe;

public abstract class Node {
    protected String name;

    abstract public void out();
}