问题描述
某OA系统需要提供一个加密模块,将用户机密信息(如:用户口令、邮箱等)加密之后再存储到数据库中,系统已经定义好了数据库操作类。为了提高开发效率,系统需要重用已有的加密算法,这些算法封装在一些由第三方提供的类中,有些甚至没有源代码,试用适配器模式设计该加密模块,实现在不修改现有类的基础上重用第三方的加密方法。
结构图
编程实现
Encode类
public interface Encode {
String encodePwd(String password);
}
适配者类(Adaptee)
public class Adaptee {
public String encodeAPI(String password){
return password.toUpperCase();
}
}
适配器类(Adapter)
public class Adapter implements Encode{
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public String encodePwd(String password) {
return adaptee.encodeAPI(password);
}
}
客户端类
public class Client {
public static void main(String[] args) {
Encode encode=new Adapter(new Adaptee());
String result=encode.encodePwd("hello");
System.out.println(result);
}
}