结构型: 组合模式

树形结构的处理

组合模式(Composite Pattern):组合多个对象形成树形结构以表示具有“整体-部分”的层次结构。组合模式对单个对象(叶子对象)和组合对象(容器对象)的使用具有一致性。

  1. 优点
    • 组合模式可以清楚定义分层次的复杂对象。
    • 组合模式为树形结构的面向对象实现提供了一种灵活的解决方案,通过叶子对象和容器对象的递归组合。
  2. 缺点
    • 在增加新构建时很难对容器中的构建类型进行限制。
  3. 适用场景
    • 整体和部分的层次结构。

1
2
3
4
5
6
public abstract class Component {
public abstract void add(Component c);
public abstract void remove(Component c);
public abstract Component getChild(int i);
public abstract void operation();
}
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 Composite extends Component {
private ArrayList<Component> children = new ArrayList<>();
@Override
public void add(Component c) {
children.add(c);
}
@Override
public void remove(Component c) {
children.remove(c);
}
@Override
public Component getChild(int i) {
return children.get(i);
}
@Override
public void operation() {
for (Component c: children){
c.operation();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Leaf extends Component {
@Override
public void add(Component c) {
// 异常或错误提示
}
@Override
public void remove(Component c) {
// 异常或错误提示
}
@Override
public Component getChild(int i) {
// 异常或错误提示
return null;
}
@Override
public void operation() {
// do sth
}
}