适配器模式
适配器思想:把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。
大白话说就是原本只能支持一种方式的方法,现在要变成可以支持多种,类似于插座跟插排的意思。
场景介绍:
(1)假设我们做一个系统V1.0,这个系统有一个接口跟一个实现类
(2)紧接着我们迭代开发V2.0时,这个系统我们定义了一个新的接口跟新的实现类
(3)但是我们同时在第二版的系统中,也是要使用老接口和老实现类
不用任何设计模式我们的思路是,同时保留两套代码。
public interface OldInterface{
void oldExecute();
}
public class OldInterfaceImpl implements OldInterface {
@Override
public void oldExecute() {
System.out.println("老版本接口实现的功能逻辑");
}
}
public interface NewInterface {
void newExecute();
}
public class NewInterfaceImpl implements NewInterface {
@Override
public void newExecute() {
System.out.println("新版本接口实现的功能逻辑");
}
}
public class TestDemo{
public static void main(String[] args) {
OldInterface oldInterface = new OldInterfaceImpl();
NewInterface newInterface = new NewInterfaceImpl();
oldInterface.oldExecute();
newInterface.newExecute();
}
}
这是不用任何设计模式写出来的代码,由上可见
我们发现这样写的代码面向的是两套规范和风格完全不同的接口,我们后期维护和理解的成本提高了。
那假设强制要求我们只能用新版接口来编写时,我们老版本就完全不能用了。我们还要重新在新版代码中再一次编写老版逻辑代码,完全没有必要。
假设我们使用适配者模式呢,让我们看看效果
在源代码的基础上加上一个适配器
// 创建一个适配器类,在这个类实现新版接口
// 引入老版接口,通过构造方法传入进来,通过新版接口的方法来实现转换
public class NewInterfaceAdapter implements NewInterface{
private OldInterface oldInterface;
//构造方法
public NewInterfaceAdapter (OldInterface oldInterface){
this.oldInterface = oldInterface;
}
@Override
public void newExecute() {
//在实现新接口的方法里调用老接口的方法,在外界看起来时用了新版的接口,实际上却是用了老版的方法
oldInterface.oldExecute();
}
}
public TestDemo1{
public static void main(String[] args) {
NewInterfaceAdapter newInterfaceAdapter = new NewInterfaceAdapter(new OldInterfaceImpl());
NewInterface newInterface = new NewInterfaceImpl();
newInterfaceAdapter.newExecute();
newInterface.newExecute();
}
}
对于调用方来说,我是调用了适配器的新版方法,我不管你底层是怎么实现的,其实我们底层是偷梁换柱了。用了老方法。
说的通俗一点就好比,我们原来只有一个双孔的插座,可是我们用一个双孔的插座连了一个三孔的插排,对于使用方来说是不知的。
使用场景:
(1)我们原来有一套直接操作数据库接口与实现类。突然这个系统的访问量上来了,数据库压力过大,我们加了redis缓存来缓解数据库压力。但是由于redis的一些操作命令与原来操作数据库的接口命名有点不一致。数据库(save,update,delete,get等)。
(2)而我们redis客户端操作命令确是,get,set,mset,mget等。
(3)在这时我们很需要一个适配器来实现我们的接口。在我们save,update,delete,get方法中去调用redis的命令。



