适配器模式
适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
这种模式涉及到一个单一的类,该类负责加入独立的或不兼容的接口功能。举个真实的例子,读卡器是作为内存卡和笔记本之间的适配器。您将内存卡插入读卡器,再将读卡器插入笔记本,这样就可以通过笔记本来读取内存卡。
我们通过下面的实例来演示适配器模式的使用。其中,音频播放器设备只能播放 mp3 文件,通过使用一个更高级的音频播放器来播放 vlc 和 mp4 文件。
类的适配器模式
package com.adapter.v1;
public class AdapterTest1 {
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee);
target.output5v();
}
}
class Adaptee {
public int output220v(){
return 220;
}
}
interface Target{
int output5v();
}
class Adapter implements Target{
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public int output5v() {
int i = adaptee.output220v();
//...
System.out.println(String.format("原始电压: %d v -> 输出电压: %d v",i,5));
return 5;
}
}
对象的适配器模式
package com.adapter.v2;
public class AdapterTest2 {
public static void main(String[] args) {
Adapter adapter = new Adapter();
adapter.output5v();
}
}
class Adaptee {
public int output220v(){
return 220;
}
}
interface Target{
int output5v();
}
//class Adapter
class Adapter extends Adaptee implements Target {
@Override
public int output5v() {
int i = output220v();
//...
System.out.println(String.format("原始电压: %d v -> 输出电压: %d v",i,5));
return 5;
}
}
应用
JDK
java.util.Arrays#asList()
java.util.Collections#list()
Spring
org.springframework.context.eventGenericApplicationListenerAdapter