设计模式-适配器模式的应用
发布日期:2021-06-30 17:44:40
浏览次数:3
分类:技术文章
本文共 2094 字,大约阅读时间需要 6 分钟。
适配器模式的应用
加密适配器
某系统需要提供一个加密模块,将用户信息(如密码等机密信息)加密之后再存储在数据库中,系统已经定义好了数据库操作类。为了提高开发效率,现需要重用已有的加密算法,这些算法封装在一些由第三方提供的类中,有些甚至没有源代码。使用适配器模式设计该加密模块,实现在不修改现有类的基础上重用第三方加密方法。 现使用适配器模式来模拟实现加密适配器的设计。用JAVA语言实现该模式。绘制该模式的UML图。
【模式UML图】
【模式代码】 // DataOperator.java:package sdp.sy_6.adapterpattern;public abstract class DataOperator { private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public abstract String doEncrypt(int key, String ps);}
// CipherAdapter.java:
package sdp.sy_6.adapterpattern;public class CipherAdapter extends DataOperator{ private Caesar cipher; public CipherAdapter() { cipher = new Caesar(); } public String doEncrypt(int key, String ps) { return cipher.doEncrypt(key, ps); }}
// NewCipherAdapter.java:
package sdp.sy_6.adapterpattern;public class NewCipherAdapter extends DataOperator{ private NewCipher cipher; public NewCipherAdapter() { cipher = new NewCipher(); } public String doEncrypt(int key, String ps) { return cipher.doEncrypt(key, ps); }}
// Caesar.java:
package sdp.sy_6.adapterpattern;public class Caesar { public String doEncrypt(int key, String ps) { return ps+key; }}
// NewCipher.java:
package sdp.sy_6.adapterpattern;public class NewCipher { public String doEncrypt(int key, String ps) { return ps+2*key; }}
// EncryptModuleMain.java:
package sdp.sy_6.adapterpattern;public class EncryptModuleMain { public static void main(String[] args) { DataOperator cipherAdapter = new CipherAdapter(); cipherAdapter.setPassword("xushicheng"); String pwd = cipherAdapter.getPassword(); System.out.println("old doEncrypt:"+cipherAdapter.doEncrypt(6, pwd)); DataOperator newCipherAdapter = new NewCipherAdapter(); newCipherAdapter.setPassword("xushicheng"); pwd = newCipherAdapter.getPassword(); System.out.println("new doEncrypt:"+newCipherAdapter.doEncrypt(6, pwd)); }}
【运行截图】
适配器模式主要适用于以下情况:
- 当系统想要使用现有的类,但是现有的类的接口不符合系统的需要时。
- 当需要通过创建一个可复用的类,使用本来的接口不相容并且无关的类结合在一起工作时。
- 在设计需要改变多个子类接口,在作用相同但名称不同的类或方法之间进行适配。
转载地址:https://lexiaoyuan.blog.csdn.net/article/details/89074239 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
很好
[***.229.124.182]2024年04月18日 20时38分25秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
强化学习(四) —— Actor-Critic演员评论家 & code
2019-04-30
RESTful API
2019-04-30
优化算法(四)——粒子群优化算法(PSO)
2019-04-30
数据在Oracle中的存储
2019-04-30
轨迹规划 trajectory planning
2019-04-30
AGV自动导引运输车
2019-04-30
Trie树(字典树)
2019-04-30
COMP7404 Machine Learing——KNN
2019-04-30
COMP7404 Machine Learing——SVM
2019-04-30
COMP7404 Machine Learing——ROC
2019-04-30
Python量子计算qiskit
2019-04-30
Python的多线程不是真的多线程(GIL全局解释器锁)
2019-04-30
Python手动读取MNIST数据集
2019-04-30