# 《Java极简设计模式》第06章:适配器模式(Adapter)

作者:冰河
星球:http://m6z.cn/6aeFbs (opens new window)
博客:https://binghe.gitcode.host (opens new window)
文章汇总:https://binghe.gitcode.host/md/all/all.html (opens new window)
源码地址:https://github.com/binghe001/java-simple-design-patterns/tree/master/java-simple-design-adapter (opens new window)

沉淀,成长,突破,帮助他人,成就自我。

  • 本章难度:★★☆☆☆
  • 本章重点:用最简短的篇幅介绍适配器模式最核心的知识,理解适配器模式的设计精髓,并能够灵活运用到实际项目中,编写可维护的代码。

大家好,我是CurleyG~~

今天给大家介绍《Java极简设计模式》的第06章,适配器模式(Adapter),多一句没有,少一句不行,用最简短的篇幅讲述设计模式最核心的知识,好了,开始今天的内容。

# 一、概述

将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

# 二、适用性

1.你想使用一个已经存在的类,而它的接口不符合你的需求。

2.你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类(即那些接口 可能不一定兼容的类)协同工作。

3.(仅适用于对象Adapter)你想使用一些已经存在的子类,但是不可能对每一个都进行 子类化以匹配它们的接口。对象适配器可以适配它的父类接口。

# 三、参与者

1.Target 定义Client使用的与特定领域相关的接口。

2.Client 与符合Target接口的对象协同。

3.Adaptee 定义一个已经存在的接口,这个接口需要适配。

4.Adapter 对Adaptee的接口与Target接口进行适配

# 四、类图


# 五、示例

Target

/**
 * @author binghe(微信 : hacker_binghe)
 * @version 1.0.0
 * @description Target接口
 * @github https://github.com/binghe001
 * @copyright 公众号: 冰河技术
 */
public interface Target {
    void adapteeMethod();
    void adapterMethod();
}
1
2
3
4
5
6
7
8
9
10
11

Adaptee

/**
 * @author binghe(微信 : hacker_binghe)
 * @version 1.0.0
 * @description 适配器类
 * @github https://github.com/binghe001
 * @copyright 公众号: 冰河技术
 */
public class Adaptee {

    public void adapteeMethod() {
        System.out.println("Adaptee method!");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

Adapter

/**
 * @author binghe(微信 : hacker_binghe)
 * @version 1.0.0
 * @description Target的实现类
 * @github https://github.com/binghe001
 * @copyright 公众号: 冰河技术
 */
public class Adapter implements Target{

    private Adaptee adaptee;

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

    @Override
    public void adapteeMethod() {
        adaptee.adapteeMethod();
    }

    @Override
    public void adapterMethod() {
        System.out.println("Adapter method!");
    }
}
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

Client

/**
 * @author binghe(微信 : hacker_binghe)
 * @version 1.0.0
 * @description 测试类
 * @github https://github.com/binghe001
 * @copyright 公众号: 冰河技术
 */
public class Test {
    public static void main(String[] args) {
        Target target = new Adapter(new Adaptee());
        target.adapteeMethod();
        target.adapterMethod();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

Result

Adaptee method!
Adapter method!
1
2

好了,今天就到这儿吧,相信大家对适配器模式有了更清晰的了解,我是冰河,我们下期见~~