适配器模式(Adapter)

1

定义

  适配器模式(Adapter):属于结构型模式,可以将某个类的接口转化为客户端期望的另一个接口表示,主要目的是兼容性,让原本因接口不匹配不能一起工作的两个类可以协同工作。

代码实战

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
interface Voltage5 {
void charge();
}

class Voltage220 {
void supply() {
System.out.println("I can supply 220V");
}
}

class Adapter extends Voltage220 implements Voltage5 {
@Override
public void charge() {
supply();
System.out.println("I can transfer to 5V");
}
}

class Test {
public static void main(String[] args) {
Adapter adapter = new Adapter();
adapter.charge();
}
}

类图

1

特点

  适配器模式的特点是,创建一个适配器,利用某个已存在的类方法,通过转换去实现某个不存在的接口功能。一般有两种实现方法,一个是继承已存在的类,另一个是持有某个已存在类的对象。

总结

  适配器模式使用的场景还是比较多的,尤其是在Android项目中,常常可以看到Adapter的身影,小伙伴们一定要牢记这种设计模式。

-------------本文结束感谢您的阅读-------------
0%