概述
适配器模式是将某个类的接口转换成客户端期望的另一个接口表示,主要目的是兼容性,让原本因接口不匹配不能一起工作的两个类可以协同工作,别名称为包装器,即将原本不兼容的接口融合在一起工作。
springMvc接受请求时的处理器适配器(处理器映射器根据映射路径找到对应的controller,处理器适配器调用该controller执行具体的逻辑并封装结果返回ModelAndView)有使用到适配器模式
主要分类
1、 类适配器模式
Adapter类通过继承src类(被适配的类)实现dst(适配接口)接口,完成str->dst的适配
场景案例:220v电压转换为5v电压给手机充电
//类适配器
public class ClassAdapterMain {
public static void main(String[] args) {
Phone phone = new Phone();
phone.charging(new VoltageAdapter());
}
}
//被适配类
class Voltage220v{
public int output220v(){
System.out.println("被适配类输出220v电压");
return 220;
}
}
//适配接口
interface Voltate5v{
//输出5v电压
int output5v();
}
//适配器类将220v电压转为5v电压
class VoltageAdapter extends Voltage220v implements Voltate5v{
@Override
public int output5v() {
//获取到220v电压
int src = output220v();
System.out.println("对220v电压进行降压处理");
//对220v电压进行降压处理
int dst = src / 44;
return dst;
}
}
//手机充电类
class Phone{
//充电
public void charging(Voltate5v voltate5v){
System.out.println("手机充电电压为:" + voltate5v.output5v());
}
}
2、 对象适配器模式(常用)
思路基本和类适配器相同,只是将Adapter类作修改,不是继承src类而是持有src类的实例,已解决兼容性问题,即持有src类实现dst接口完成src->dst的适配
//对象适配器
public class ObjectAdapterMain {
public static void main(String[] args) {
Phone phone = new Phone();
phone.charging(new VoltageAdapter(new Voltage220v()));
}
}
//被适配类
class Voltage220v{
public int output220v(){
System.out.println("被适配类输出220v电压");
return 220;
}
}
//适配接口
interface Voltate5v{
//输出5v电压
int output5v();
}
//适配器类将220v电压转为5v电压
class VoltageAdapter implements Voltate5v{
private Voltage220v voltage220v; //被适配的类由继承变为聚合的关系
public VoltageAdapter(Voltage220v voltage220v){
this.voltage220v = voltage220v;
}
@Override
public int output5v() {
//获取到220v电压
int src = voltage220v.output220v();
System.out.println("对220v电压进行降压处理");
//对220v电压进行降压处理
int dst = src / 44;
return dst;
}
}
//手机充电类
class Phone{
//充电
public void charging(Voltate5v voltate5v){
System.out.println("手机充电电压为:" + voltate5v.output5v());
}
}
3、 接口适配器模式
适用于一个接口不想使用其所有方法的情况,即:
当不需要实现接口提供的全部方法时,可先设计一个抽象类实现接口,并为该接口中的每个方法提供一个默认实现(空方法),那么该抽象类的子类可选择性的覆盖某些方法来显示需求
//接口适配器
public class InterfaceAdapterMain {
public static void main(String[] args) {
//只使用接口中的方法3
/*使用匿名内部类的方式实现
InterfaceAdapter adapter = new InterfaceAdapter() {
@Override
public void operation3() {
System.out.println("使用了接口IInterface的3方法");
}
};
adapter.operation3();*/
//使用子类继承的方式实现
SonClass sonClass = new SonClass();
sonClass.operation3();
}
}
//接口,多个方法
interface IInterface{
void operation1();
void operation2();
void operation3();
}
//接口适配抽象类,实现接口,默认实现空方法
abstract class InterfaceAdapter implements IInterface{
@Override
public void operation1() { }
@Override
public void operation2() { }
@Override
public void operation3() { }
}
//抽象类的子类
class SonClass extends InterfaceAdapter{
@Override
public void operation3() {
System.out.println("使用了接口IInterface的3方法");
}
}