我们知道Java里共有23种设计模式,可以使原本因接口不匹配而导致无法在一起工作的两个类能够一起工作,适配器模式属于结构型设计模式。
适配器模式
定义
适配器模式又叫变压器模式,它的功能是将一个类的接口变成客户端所期望的另一种接口。
适用场景
(1) 已经存在的类,它的方法和需求不匹配(方法结果相同或相似)的情况。
(2) 随着软件的升级维护,由于不同的产品,不同的厂家造成功能类似而接口不同情况下的解决方案。
优点
(1) 能提高类的透明性和复用性,现有的类不需要改变。
(2) 目标类和适配器类解耦,提高程序的扩展性。
(3) 很多业务场景中符合开闭原则。
缺点
(1) 适配器编写过程中需要全面考虑,可能会增加系统复杂性。
(2) 增加代码阅读难度,降低代码可读性,过多使用适配器会使系统变得凌乱。
实例
类适配器实例
类适配器的原理是通过继承来实现适配器功能。
/**
* 源角色 系统中存在
*/
public class AC220 {
public int outputAC220() {
return 220;
}
}
/**
* 目标角色 也就是期望的接口
*/
public interface DC5 {
int outputDC5();
}
/**
* 适配器角色 将源角色转为目标角色的类
*/
public class PowerAdapter extends AC220 implements DC5 {
@Override
public int outputDC5() {
int adapterInput = super.outputAC220();
int adapterOutput = adapterInput / 44;
System.out.println("输入电压:" + adapterInput + "V,输出电压:" + adapterOutput + "V");
return adapterOutput;
}
}
对象适配器实例
对象适配器的原理是通过组合来实现适配器功能。
/**
* 源角色 系统中存在
*/
public class AC220 {
public int outputAC220() {
return 220;
}
}
/**
* 目标角色 也就是期望的接口
*/
public interface DC5 {
int outputDC5();
}
/**
* 适配器角色 将源角色转为目标角色的类
*/
public class PowerAdapter implements DC5 {
//组合方式实现对象适配器
AC220 ac220;
public PowerAdapter(AC220 ac220) {
this.ac220 = ac220;
}
@Override
public int outputDC5() {
int adapterInput = ac220.outputAC220();
int adapterOutput = adapterInput / 44;
System.out.println("输入电压:" + adapterInput + "V,输出电压:" + adapterOutput + "V");
return adapterOutput;
}
}
接口适配器实例
接口适配器的关注点与类适配器和对象适配器关注点不一样,类适配器和对象适配器着重于将系统存在的一个角色转化成目标角色。而接口适配器的使用场景是解决接口方法过多,如果直接实现接口,那么类会出现许多空的实现方法,此时使用接口适配器就能让我们[只实现我们所需的接口方法],其原理就是利用抽象类实现接口。
/**
* 源角色 系统中存在
*/
public class AC220 {
public int outputAC220() {
return 220;
}
}
/**
* 目标角色 也就是期望的接口
*/
public interface DC {
int outputDC5();
int outputDC12();
int outputDC24();
int outputDC36();
}
/**
* 适配器角色 将源角色转为目标角色的类
*/
public class PowerAdapter implements DC {
AC220 ac220;
public PowerAdapter(AC220 ac220) {
this.ac220 = ac220;
}
@Override
public int outputDC5() {
int adapterInput = ac220.outputAC220();
int adapterOutput = adapterInput / 44;
System.out.println("输入电压:" + adapterInput + "V,输出电压:" + adapterOutput + "V");
return adapterOutput;
}
@Override
public int outputDC12() {
int adapterInput = ac220.outputAC220();
int adapterOutput = adapterInput / 18;
System.out.println("输入电压:" + adapterInput + "V,输出电压:" + adapterOutput + "V");
return 0;
}
@Override
public int outputDC24() {
return 24;
}
@Override
public int outputDC36() {
return 36;
}
}