适配器模式

1 概念

1 定义

将一个类的接口转换成客户期望的另一个接口。使得原本不兼容的类,可以一起工作

类型:结构型

分类:

对象适配器:使用组合

类适配器:使用类继承

2 适用场景

  • 已经存在的类,他的方法和需求不匹配时(方法的结果相同或相似)
  • 不是软件设计阶段考虑的设计模式,是随着软件的维护,由于不同产品,不同厂家造成功能类似而接口不相同情况下的解决方案

3 优缺点

优点:

  • 提高类的透明性和复用,现有的类复用而不发生改变
  • 目标类和适配器类解耦,提高程序扩展性
  • 符合开闭原则

缺点:

增加代码可读性的难度

2 代码

场景:将220V直流电,通过充电器转换成5V的交流电,从而给手机充电

2.1 类适配器模式

1
2
3
4
5
6
7
8
// 被适配者
public class AC220 {
public int outputAC220V(){
int output = 220;
System.out.println("输出交流电"+output+"V");
return output;
}
}
1
2
3
4
// 目标输出
public interface DC5 {
int outputDC5V();
}
1
2
3
4
5
6
7
8
9
10
11
// 适配器,使被适配者转换成目标类,并且有目标输出的接口方法
public class PowerAdapter extends AC220 implements DC5{
@Override
public int outputDC5V() {
int adapterInput = super.outputAC220V();
//变压器...
int adapterOutput = adapterInput/44;
System.out.println("使用PowerAdapter输入AC:"+adapterInput+"V"+"输出DC:"+adapterOutput+"V");
return adapterOutput;
}
}
1
2
3
4
5
6
public class Test {
public static void main(String[] args) {
Target adapterTarget = new Adapter();
adapterTarget.request();
}
}

2.2 对象适配器

只有适配器的代码发生了改变

1
2
3
4
5
6
7
8
9
10
11
12
13
public class PowerAdapter implements DC5{
// 这里使用组合的方式,将被适配者组合到了当前类
private AC220 ac220 = new AC220();

@Override
public int outputDC5V() {
int adapterInput = ac220.outputAC220V();
//变压器...
int adapterOutput = adapterInput/44;
System.out.println("使用PowerAdapter输入AC:"+adapterInput+"V"+"输出DC:"+adapterOutput+"V");
return adapterOutput;
}
}

适配器模式
http://example.com/适配器模式/
作者
Panyurou
发布于
2023年10月3日
许可协议