组合模式

组合模式也叫合成模式,有时又叫部分整体模式,主要是用来描述部分与整体的关系;

只要是树形结构, 就要考虑使用组合模式, 只要是要体现局部和整体的关系的时候, 而且这种关系还可能比较深, 考虑使用组合模式。

定义

将对象组合成树形结构以表示部分—整体的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

实现

组合模式一般用来描述整体与部分的关系,它将对象组织到树形结构中,顶层的节点被称为根节点,根节点下面可以包含树枝节点和叶子节点,树枝节点下面又可以包含树枝节点和叶子节点。

组合模式通用类图

组合模式分为透明式的组合模式安全式的组合模式

透明式的组合模式中,抽象构件声明了所有子类中的全部方法,所以客户端无须区别树叶对象和树枝对象,对客户端来说是透明的。

缺点是树叶构件本来没有 add()remove()getChild() 方法,却要实现它们,空实现或抛异常,会带来一些安全性问题。

Component抽象构件角色,其主要作用是为树叶构件和树枝构件声明公共接口,并实现它们的默认行为。在透明式的组合模式中抽象构件还声明访问和管理子类的接口;在安全式的组合模式中不声明访问和管理子类的接口,管理工作由树枝构件完成。

1
2
3
4
5
6
7
8
9
public interface Component {
void add(Component c);

void remove(Component c);

Component getChild(int i);

void operation();
}

Leaf树叶构件角色,是组合中的叶节点对象,它没有子节点,用于继承或实现抽象构件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Leaf implements Component {
private String name;
public Leaf(String name) {
this.name = name;
}
public void add(Component c) {
}
public void remove(Component c) {
}
public Component getChild(int i) {
return null;
}
public void operation() {
System.out.println("树叶" + name + ":被访问!");
}
}

Composite树枝构件角色 / 中间构件,是组合中的分支节点对象,它有子节点,用于继承和实现抽象构件。它的主要作用是存储和管理子部件,通常包含 add()remove()getChild() 等方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Composite implements Component {
private ArrayList<Component> children = new ArrayList<>();

public void add(Component c) {
children.add(c);
}

public void remove(Component c) {
children.remove(c);
}

public Component getChild(int i) {
return children.get(i);
}

public void operation() {
for (Object obj : children) {
((Component) obj).operation();
}
}
}

客户端使用:

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {
Component c0 = new Composite();
Component c1 = new Composite();
Component leaf1 = new Leaf("1");
Component leaf2 = new Leaf("2");
Component leaf3 = new Leaf("3");
c0.add(leaf1);
c0.add(c1);
c1.add(leaf2);
c1.add(leaf3);
c0.operation();
}

安全式的组合模式中,将管理子构件的方法移到树枝构件中抽象构件和树叶构件没有对子对象的管理方法,这样就避免了上一种方式的安全性问题,但由于叶子和分支有不同的接口,客户端在调用时要知道树叶对象和树枝对象的存在,所以失去了透明性

安全式的组合模式与透明式组合模式的实现代码类似,只要对其做简单修改就可以了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public interface Component {
void operation();
}

public static void main(String[] args) {
Composite c0 = new Composite();
Composite c1 = new Composite();
Component leaf1 = new Leaf("1");
Component leaf2 = new Leaf("2");
Component leaf3 = new Leaf("3");
c0.add(leaf1);
c0.add(c1);
c1.add(leaf2);
c1.add(leaf3);
c0.operation();
}

优点

  • 简化客户端代码,使客户端代码可一致地处理单个对象和组合对象,无须关心处理的是单个对象,还是组合对象
  • 更容易在组合体内加入新的对象,客户端不会因为加入了新的对象而更改源代码,满足开闭原则

缺点

  • 设计较复杂,客户端需要花更多时间理清类之间的层次关系
  • 不容易限制容器中的构件
  • 容易用继承的方法来增加构件的新功能

应用

在需要表示一个对象整体与部分的层次结构的场合;要求对用户隐藏组合对象与单个对象的不同,用户可以用统一的接口使用组合结构中的所有对象的场合;