某系统需要提供一个加密模块,将用户信息加密之后再存储在数据库中,系统已经定义好了数据库操作类。为了提高效率,现需要重用已有的加密算法,这些加密算法封装在一些由第三方提供的类中,有些甚至没有源代码。要求不修改现有类的基础上重用第三方加密算法。现使用对象适配器模式完成该系统设计。
package com.lanqiao.dmeo6;
/**
* Caesar类是一个由第三方提供的数据加密类,该类为final类,无法继承
* 因此本实例只能对象适配器模式
*
* @author QqiDchunGlin
*
*/
public final class Caesar {
public String doEncrypt(int key, String psd) {
String str = "";
for (int i = 0; i < psd.length(); i++) {
char c = psd.charAt(i);
if(c>='a' && c<='z') {
c += key % 26;
if(c<'a') {
c +=26;
}
if(c>'z') {
c -= 26;
}
}
if(c>='A' && c<='Z') {
c+= key %26;
if(c<'A') {
c += 26;
}
if(c>'Z') {
c -= 26;
}
}
str += c;
}
return str;
}
}
package com.lanqiao.dmeo6;
public class CipherAdapter extends DataOperator{
private Caesar ciphter;
public CipherAdapter() {
ciphter = new Caesar();
}
//有参构造方法
public CipherAdapter(Caesar ciphter) {
super();
this.ciphter = ciphter;
}
public String doEncrypt(int key,String psd) {
String str = ciphter.doEncrypt(key,psd);
return str;
}
}
package com.lanqiao.dmeo6;
public abstract class DataOperator {
private String passWord;//密码
public String getPassword() {
return passWord;
}
public void setPassword(String psd) {
this.passWord = psd;
}
//加密算法
public abstract String doEncrypt(int key,String psd);
}
package com.lanqiao.dmeo6;
/**
* @author QqiDchunGlin
*
*/
public class Test {
public static void main(String[] args) {
DataOperator dao = new CipherAdapter();
dao.setPassword("whoami");
String psd = dao.getPassword();
String str = dao.doEncrypt(6, psd);
System.out.println("明文为:"+psd);
System.out.println("密文为:"+str);
}
}