适配器模式(Adapter Pattern)
顾名思义,适配器模式是作为桥梁来沟通两个不相关的接口或者类,属于结构型模式。例如:手机的适配器将220v的电压转换成手机可以充电的电压。读卡器使内存卡可以插入电脑进行读取。
实现方式
适配器继承或依赖已有的对象,实现想要的目标接口。但需要注意的是,适配器模式并不是设计时所用的模式,在设计时,如果能设计能够完整切合的两个类就不要使用适配器模式,适配器模式是后期解决正在使用中的系统扩展功能使用的。过多地使用适配器,会让系统非常零乱,不易整体进行把握。除非有非常详细的文档,但是尽管如此,在后期维护的时候,也不能一目了然的看到调用的究竟是哪个类中的方法。
适配器模式设计的角色
● 目标(Target)角色:这就是所期待得到的接口。注意:由于这里讨论的是类适配器模式,因此目标不可以是类。
● 源(Adapee)角色:现在需要适配的接口。
● 适配器(Adaper)角色:适配器类是本模式的核心。适配器把源接口转换成目标接口。显然,这一角色不可以是接口,而必须是具体类。
代码实现
类适配器
首先我们先创建一个接口,有唱歌和跳舞两个功能。1
2
3
4
5
6
7
8
9
10
11
12package com.lizx.adapter_1;
/**
* 接口
*
* @date 2018/2/12 19:00:22
* @auther Pyctay
*/
public interface Target {
void sing();
void dance();
}
然后我们有一个类具有唱歌的功能。1
2
3
4
5
6
7
8
9
10
11
12
13package com.lizx.adapter_1;
/**
* 源类
*
* @date 2018/2/12 19:03:57
* @auther Pyctay
*/
public class Source {
public void sing(){
System.out.println("Singing..");
}
}
我们使用一个适配器类继承源类,实现接口。1
2
3
4
5
6
7
8
9
10
11
12
13
14package com.lizx.adapter_1;
/**
* 适配器
*
* @date 2018/2/12 19:05:24
* @auther Pyctay
*/
public class Adapter extends Source implements Target {
@Override
public void dance() {
System.out.println("Dancing..");
}
}
最后有一个测试类。1
2
3
4
5
6
7
8
9
10package com.lizx.adapter_1;
public class Main {
public static void main(String[] args) {
Adapter adapter = new Adapter();
adapter.sing();
adapter.dance();
}
}
输出结果:
对象适配器
在对象适配器中,适配器不继承源类,而是维护一个源类的对象,使用构造参数传入源类的对象。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25package com.lizx.adapter_2;
/**
* 适配器
*
* @date 2018/2/12 19:05:24
* @auther Pyctay
*/
public class Adapter implements Target {
private static Source source;
public Adapter(Source source) {
this.source = source;
}
@Override
public void sing() {
source.sing();
}
@Override
public void dance() {
System.out.println("Dancing..");
}
}
输出结果:
完整代码实现:https://github.com/pyctay/adapter.git
同时欢迎关注我的微信公众号:猿人族永不为奴。
二维码: