适配器模式
具体说适配器模式之前,先来说说适配器模式在哪些地方使用过。
1).首先就是Sun公司推出的数据库连接工具JDBC,JDBC给出了客户端通用的抽象接口,每一个具体的数据库引擎的JDBC驱动都是介于JDBC驱动和数据库引擎之间的适配器。
2).另一个就是spring AOP里的通知Advice,在spring 的AOP中,BeforeAdvice,AfterAdvice ,ThrowsAdvice这三种通知都是借助适配器模式来实现的,好处就是用户可以向框架中加入自己想要的任何一种通知类型。
认识适配器模式
1)定义:把一个接口转换成用户希望的另一个接口,使的原本不兼容而不能一起工作的类可以一起工作。别名也叫包装器。此外要注意适配器模式可作为类适配器模型也可以作为对象适配器模型。
2)角色:Target(魔表抽象类),Adapter(适配器类),Adaptee(适配这者类)
模式详解
(一)类适配器
public class Adapter extends Adaptee implements Target
{
public void request(){
super.request();
}
}
(二)对象适配器
public class Adapter extends Target
{
private Adaptee adaptee;
public Adapter(Adaptee adaptee){
this.adaptee = adaptee;
}
public void request(){
adaptee.request();
}
}
对象适配器模式在spring里可以通过容器注入。
下面 通过一个需求来说明适配器模式
例子:某系统需要提供一个加密模块,将用户密码加密之后存入到数据库,为提高开发效率,需要重用已有的加密算法凯撒加密也就是Caesar类。
/**
* @author chunchun
*@date 2021年1月2日
* @projectname Design_pattern
* 目标抽象类,目标数据操作类,相当于target
*/
public abstract class DataOperstion {
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public abstract String doencrypt(int key, String pass);
}
/**
* @author chunchun
*@date 2021年1月2日
* @projectname Design_pattern
* 适配者类,执行数据加密(凯撒加密)
* 定义为final无法继承,所以只能使用对象适配器来实现适配
*/
public final class Caesar {
public String doEncrypt(int key ,String ps) {
String es = "";
for(int i = 0;i<ps.length();i++) {
char c = ps.charAt(i);
if(c>='a'&&c<='z') {
c += key%26;
if(c>'z')c-=26;
if(c<'a')c+=26;
}
if(c>='A'&&c<='Z') {
c += key%26;
if(c>'Z')c-=26;
if(c<'A')c+=26;
}
es+=c;
}
return es;
}
}
/**
* @author chunchun
*@date 2021年1月2日
* @projectname Design_pattern
* 适配器类实现加密适配
*/
public class CipherAdapter {
//对象适配注入,不要new
private Caesar caesar;
public CipherAdapter() {
caesar = new Caesar();
}
public String doEncrypt(int key, String ps) {
return caesar.doEncrypt(key, ps);
}
public static void main(String[] args) {
CipherAdapter cipherAdapter = new CipherAdapter();
String encryption = cipherAdapter.doEncrypt(2, "zzc");
System.out.println(encryption);
}
}
设计模式需要结合源码会受益良多。