组合模式

整体和部分统一

场景


对部分和整体统一建模
外界逻辑不区分结构,和内部结构解耦
适合树形层次结构

代码


Sample
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
37
public interface Component {
int getCount();
}

//leaf node
public class SimpleComponent implements Component {
private int cnt;
public SimpleComponent(int cnt) {
this.cnt = cnt;
}

@Override
public int getCount() {
return cnt;
}
}

//non-leaf node
public class ComplexComponent implements Component {
private List<Component> subList;
public ComplexComponent() {
subList = new ArrayList<>();
}

public void addComponent(Component c) {
subList.add(c);
}

@Override
public int getCount() {
int cnt = 0;
for(Component c : subList) {
cnt += c.getCount();
}
return cnt;
}
}

优缺点


因为不同组件提供方法不同,因此构建时需要使用实现类构建

应用


java.awt.Container