组合模式(Composite Pattern)

2024/3/28 Java进阶

将对象组合成树形结构以表示"部分-整体"的层次结构。允许用户自由构建单独的对象和组合对象。

# 1、组合模式案例

通过案例自由构建类似如下的树形结构、

root
--A
----A2
--B
----B2
-------B3
--C
----C2
1
2
3
4
5
6
7
8
public abstract class Node {

    protected String name;

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

    public void print(){
        print(0);
    }

    abstract public void print(int level);

    abstract public void add(Node node);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class CompositeNode extends Node{

    private List<Node> nodeList;

    public CompositeNode(String name) {
        super(name);
        nodeList = new ArrayList<>();
    }

    @Override
    public void print(int level) {
        for (int i = 0; i < level; i++) {
            System.out.print("--");
        }
        System.out.println(name+"("+level+")");
        for (Node node : nodeList) {
            node.print(level+1);
        }
    }

    @Override
    public void add(Node node) {
        nodeList.add(node);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class ClientTest {
    public static void main(String[] args) {
        Node root = new CompositeNode("root");
        
        Node A = new CompositeNode("A");
        Node A2 = new CompositeNode("A2");
        
        Node B = new CompositeNode("B");
        Node B2 = new CompositeNode("B2");
        Node B3 = new CompositeNode("B3");
        
        Node C = new CompositeNode("C");
        Node C2 = new CompositeNode("C2");

        root.add(A);
        root.add(B);
        root.add(C);

        A.add(A2);
        B.add(B2);
        B2.add(B3);
        C.add(C2);

        root.print();
    }
}
/** 输出结果:
root(0)
--A(1)
----A2(2)
--B(1)
----B2(2)
------B3(3)
--C(1)
----C2(2)
 * /
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36