设计模式之适配器模式!

适配器模式它将不兼容的接口转换为可兼容的接口,让原本由于接口不兼容而不能一起工作的类可以一起工作。

适配器模式有两种实现方式:类适配器和对象适配器。

  • 类适配器使用继承关系来实现,对象适配器使用组合关系来实现。

UML类图:

img

代码实现

ITarget 表示要转化成的接口定义。

Adaptee 是一组不兼容 ITarget 接口定义的接口,Adaptor 将 Adaptee 转化成一组符合 ITarget 接口定义的接口。

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// 类适配器: 基于继承
public interface ITarget {
void f1();
void f2();
void fc();
}
public class Adaptee {
public void fa() { //... }
public void fb() { //... }
public void fc() { //... }
}
public class Adaptor extends Adaptee implements ITarget {
public void f1() {
super.fa();
}

public void f2() {
//...重新实现f2()...
}

// 这里fc()不需要实现,直接继承自Adaptee,这是跟对象适配器最大的不同点
}


// 对象适配器:基于组合
public interface ITarget {
void f1();
void f2();
void fc();
}
public class Adaptee {
public void fa() { //... }
public void fb() { //... }
public void fc() { //... }
}
public class Adaptor implements ITarget {
private Adaptee adaptee;

public Adaptor(Adaptee adaptee) {
this.adaptee = adaptee;
}

public void f1() {
adaptee.fa(); //委托给Adaptee
}

public void f2() {
//...重新实现f2()...
}

public void fc() {
adaptee.fc();
}
}

如何选择

如果 Adaptee 接口并不多,那两种实现方式都可以。

如果 Adaptee 接口很多,而且 Adaptee 和 ITarget 接口定义大部分都相同,那推荐使用类适配器。

  • 因为 Adaptor 复用父类 Adaptee 的接口,比起对象适配器的实现方式,Adaptor 的代码量要少一些。

如果 Adaptee 接口很多,而且 Adaptee 和 ITarget 接口定义大部分都不相同,那推荐使用对象适配器。

  • 因为组合结构相对于继承更加灵活。

应用场景

封装有缺陷的接口设计:

假设依赖的外部系统在接口设计方面有缺陷(比如包含大量静态方法),引入之后会影响到自身代码的可测试性。

为了隔离设计上的缺陷,希望对外部系统提供的接口进行二次封装,抽象出更好的接口设计,这个时候就可以使用适配器模式了。

统一多个类的接口设计:

假设系统要对用户输入的文本内容做敏感词过滤,为了提高过滤的召回率,引入了多款第三方敏感词过滤系统。

  • 依次对用户输入的内容进行过滤,过滤掉尽可能多的敏感词。

但是,每个系统提供的过滤接口都是不同的,这就意味着没法复用一套逻辑来调用各个系统。

这个时候,就可以使用适配器模式,将所有系统的接口适配为统一的接口定义,这样可以复用调用敏感词过滤的代码。