Java适配器模式
适配器模式将一个类的接口转换成客户端期望的接口。
模式定义
意图:将不兼容接口转换为兼容接口,让原本不兼容的类可以合作。
两类适配器
| 类型 | 实现方式 | 特点 |
|---|---|---|
| 类适配器 | 继承 | 灵活性低 |
| 对象适配器 | 组合 | 灵活性高 |
类适配器
Java
// 目标接口
public interface Target {
void request();
}
// 已存在类(不兼容)
public class Adaptee {
public void specificRequest() {
System.out.println("特殊请求");
}
}
// 类适配器(继承)
public class ClassAdapter extends Adaptee implements Target {
@Override
public void request() {
specificRequest(); // 转换调用
}
}
// 使用
Target target = new ClassAdapter();
target.request();
对象适配器(推荐)
Java
// 对象适配器(组合)
public class ObjectAdapter implements Target {
private Adaptee adaptee; // 组合
public ObjectAdapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest(); // 转换调用
}
}
// 使用
Target target = new ObjectAdapter(new Adaptee());
target.request();
双向适配器
Java
public class TwoWayAdapter implements Target, AdapteeInterface {
private Target target;
private Adaptee adaptee;
public TwoWayAdapter(Target target) {
this.target = target;
}
public TwoWayAdapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest();
}
@Override
public void specificRequest() {
target.request();
}
}
实际应用示例
电压适配器
Java
// 目标接口(220V)
public interface Voltage220 {
int output220V();
}
// 已存在类(110V)
public class Voltage110 {
public int output110V() {
return 110;
}
}
// 适配器
public class VoltageAdapter implements Voltage220 {
private Voltage110 voltage110;
public VoltageAdapter(Voltage110 voltage110) {
this.voltage110 = voltage110;
}
@Override
public int output220V() {
int voltage = voltage110.output110V();
return voltage * 2; // 适配转换
}
}
接口转换
Java
// 旧接口
public interface LegacyService {
String getData(int id);
}
// 新接口
public interface ModernService {
DataResponse fetch(int id);
}
public class DataResponse {
private String data;
private int status;
}
// 适配器
public class ServiceAdapter implements ModernService {
private LegacyService legacyService;
public ServiceAdapter(LegacyService legacyService) {
this.legacyService = legacyService;
}
@Override
public DataResponse fetch(int id) {
String data = legacyService.getData(id);
return new DataResponse(data, 200);
}
}
Java内置适配器
InputStreamReader
Java
// InputStream(字节流)→ Reader(字符流)
InputStream inputStream = new FileInputStream("file.txt");
Reader reader = new InputStreamReader(inputStream); // 适配器
Arrays.asList()
Java
// 数组 → List
String[] array = {"a", "b", "c"};
List<String> list = Arrays.asList(array); // 适配器
类适配器 vs 对象适配器
| 特性 | 类适配器 | 对象适配器 |
|---|---|---|
| 实现方式 | 继承 | 组合 |
| 灵活性 | 低 | 高 |
| 适配多个类 | 不支持 | 支持 |
| 推荐程度 | 较低 | 推荐 |
适用场景
- 已有类接口不兼容
- 需要统一多个类的接口
- 需要复用现有类
- 不想修改原有代码
注意事项
对象适配器更灵活,推荐使用
适配器不应添加太多功能,保持简单
不要滥用适配器,优先考虑重构接口
适配器是补救模式,应在设计阶段避免需要
要点总结
- 适配器转换不兼容接口为兼容接口
- 类适配器通过继承,对象适配器通过组合
- 对象适配器更灵活,可适配多个类
- Java中InputStreamReader等是典型应用
- 适用于遗留系统整合、接口统一场景
📝 发现内容有误?点击此处直接编辑