组合模式适合表示部分-整体, 例如大学-院系、部门-企业等。
类结构
代码
1package com.elltor.designpattern.compose;
2
3public abstract class Component {
4 protected String componentName;
5
6
7 public Component(String componentName) {
8 this.componentName = componentName;
9 }
10
11 public abstract void add(Component component);
12
13 public abstract void remove(Component component);
14
15 public abstract void show(int depth);
16}
1package com.elltor.designpattern.compose;
2
3import java.util.ArrayList;
4import java.util.List;
5
6public class Composite extends Component {
7 private List<Component> childList = new ArrayList<>();
8
9 public Composite(String componentName) {
10 super(componentName);
11 }
12
13 @Override
14 public void add(Component component) {
15 childList.add(component);
16 }
17
18 @Override
19 public void remove(Component component) {
20 childList.remove(component);
21 }
22
23 @Override
24 public void show(int depth) {
25 for(int i=0;i<depth;i++){
26 System.out.print('+');
27 }
28
29 System.out.println(componentName);
30
31 for(int i=0;i<childList.size();i++){
32 childList.get(i).show(depth+2);
33 }
34 }
35}
1package com.elltor.designpattern.compose;
2
3public class Leaf extends Component {
4 public Leaf(String componentName) {
5 super(componentName);
6 }
7
8 @Override
9 public void add(Component component) {
10 System.out.println("叶子节点无法增加节点");
11 }
12
13 @Override
14 public void remove(Component component) {
15 System.out.println("叶子节点无法删除节点");
16 }
17
18 @Override
19 public void show(int depth) {
20 for (int i = 0; i < depth; i++) {
21 System.out.print('+');
22 }
23 System.out.println(componentName);
24 }
25}
1package com.elltor.designpattern.compose;
2
3public class Main {
4 public static void main(String[] args) {
5 Composite root = new Composite("树根");
6 root.add(new Leaf("叶子A"));
7 root.add(new Leaf("叶子B"));
8
9 Composite composite1 = new Composite("节点X");
10 composite1.add(new Leaf("叶子XA"));
11 composite1.add(new Leaf("叶子XB"));
12
13 Composite composite2 = new Composite("节点Y");
14 composite2.add(new Leaf("叶子YA"));
15 composite2.add(new Leaf("叶子YB"));
16
17 composite1.add(composite2);
18 root.add(composite1);
19
20 root.show(0);
21 }
22}
23
24// 打印
25+树根
26+++叶子A
27+++叶子B
28+++节点X
29+++++叶子XA
30+++++叶子XB
31+++++节点Y
32+++++++叶子YA
33+++++++叶子YB