一. 前言

1. 定义

Adapter Pattern:定义一个包装类,用于包装不兼容接口的对象。

  1. 包装类 = 适配器Adapter。
  2. 被包装对象 = 适配者Adaptee = 被适配的类。

作用:

把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法一起工作的两个类能够在一起工作。

二. 类的适配器模式

1. 概述

冲突:Target期待调用Request方法,而Adaptee并没有(这就是所谓的不兼容了)。

解决方案:为使Target能够使用Adaptee类里的SpecificRequest方法,故提供一个中间环节Adapter类(继承Adaptee & 实现Target接口),把Adaptee的API与Target的API衔接起来(适配)。

2. 代码

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
public class ClassAdapter {
/**
* 目标接口:Target
*/
public interface Target {
void request();
}

/**
* 源类:Adaptee
*/
public static class Adaptee {
public void selfRequest(){
System.out.println("被调用了");
}
}

/**
* 适配器类
*/
public static class Adapter extends Adaptee implements Target {

@Override
public void request() {
this.selfRequest();
}
}

/**
* 测试
*/
public static void main(String[] args) {
Adapter adapter = new Adapter();
adapter.request();
}
}

三. 对象的适配器模式

1. 1. 概述

冲突:Target期待调用Request方法,而Adaptee并没有(这就是所谓的不兼容了)。

解决方案:为使Target能够使用Adaptee类里的SpecificRequest方法,故提供一个中间环节Adapter类(继承Adaptee & 实现Target接口),把Adaptee的API与Target的API衔接起来(适配)。

2. 代码

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
public class ObjectAdapter {
/**
* 目标接口:Target
*/
public interface Target {
void request();
}

/**
* 源类:Adaptee
*/
public static class Adaptee {
public void selfRequest(){
System.out.println("被调用了");
}
}

/**
* 适配器类
*/
public static class Adapter extends Adaptee implements Target {

Adaptee adaptee;

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

@Override
public void request() {
adaptee.selfRequest();
}
}

/**
* 测试
*/
public static void main(String[] args) {
Adapter adapter = new Adapter(new Adaptee());
adapter.request();
}
}

四. Android系统中的使用

ListView和RecyclerView的Adapter。

五. 优缺点以及应用场景

1. 优点

  • 更好的复用性:系统需要使用现有的类,而此类的接口不符合系统的需要。那么通过适配器模式就可以让这些功能得到更好的复用。

  • 透明、简单:客户端可以调用同一接口,因而对客户端来说是透明的。这样做更简单 & 更直接

  • 更好的扩展性:在实现适配器功能的时候,可以调用自己开发的功能,从而自然地扩展系统的功能。

  • 解耦性:将目标类和适配者类解耦,通过引入一个适配器类重用现有的适配者类,而无需修改原有代码

  • 符合开放-关闭原则:同一个适配器可以把适配者类和它的子类都适配到目标接口;可以为不同的目标接口实现不同的适配器,而不需要修改待适配类

2. 缺点

过多的使用适配器,会让系统非常零乱,不易整体进行把握。

3. 应用场景

  • 系统需要复用现有类,而该类的接口不符合系统的需求,可以使用适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作

  • 多个组件功能类似,但接口不统一且可能会经常切换时,可使用适配器模式,使得客户端可以以统一的接口使用它们

参考文章

适配器模式(Adapter Pattern)- 最易懂的设计模式解析

Android的设计模式-适配器模式