一、实验目的:
1) 掌握适配器模式(Adapter)的特点
2) 分析具体问题,使用适配器模式进行设计。
二、实验环境:
IDEA
三、实验内容:
加密适配器
某系统需要提供一个加密模块,将用户信息(如密码等机密信息)加密之后再存储在数据库中,系统已经定义好了数据库操作类。为了提高开发效率,现需要重用已有的加密算法,这些算法封装在一些由第三方提供的类中,有些甚至没有源代码。使用适配器模式设计该加密模块,实现在不修改现有类的基础上重用第三方加密方法。
现使用适配器模式来模拟实现打印池的设计。用JAVA语言实现(C#控制台应用程序实现)该模式。绘制该模式的UML图。
【模式UML图】
【模式代码(JAVA语言实现)】
public abstract class DataOperation {
public abstract String doEncrypt(String ps);
}
public class CipherAdapter extends DataOperation {
private Caesar cipher;
public CipherAdapter() {
cipher=new Caesar();
}
public String doEncrypt(String ps) {
return cipher.doEncrypt(ps);
}
}
public class Caesar {
public String doEncrypt(String ps) {
return "原来加密方法加密之后的"+ps;
}
}
public class NewCipherAdapter extends DataOperation {
private NewCipher cipher;
public NewCipherAdapter() {
cipher=new NewCipher();
}
public String doEncrypt(String ps) {
return cipher.doEncrypt(ps);
}
}
public class NewCipher {
public String doEncrypt(String ps) {
return "新加密方法加密之后的"+ps;
}
}
public class Client {
public static void main(String[] args) {
String s1 = "123456";
String s2 = "";
DataOperation data = null;
data = new CipherAdapter();
s2 = data.doEncrypt(s1);
System.out.println(s2);
data = new NewCipherAdapter();
s2 = data.doEncrypt(s1);
System.out.println(s2);
}
}
【运行截图】
四、心得体会:
适配器模式主要适用于以下情况:
1)统需要使用一些现有的类,而这些类的接口(如方法名)不符合系统的需要,甚至没有这些类的源代码。
2)创建一个可以重复使用的类,用于与一些彼此之间没有太大关联的一些类,包括一些可能在将来引进的类一起工作。