问题
Sunny软件公司欲开发了一个数据加密模块,可以对字符串进行加密。最简单的加密算法通过对字母进行移位来实现,同时还提供了稍复杂的逆向输出加密,还提供了更为高级的求模加密。用户先使用最简单的加密算法对字符串进行加密,如果觉得还不够可以对加密之后的结果使用其他加密算法进行二次加密,当然也可以进行第三次加密。试使用装饰模式设计该多重加密系统。
/**
* 抽象加密类
* @author 李亚杰
* @date 2024/4/16 16:51
* @description Encryption
*/
public abstract class Encryption {
abstract protected String encode(String s);
}
/**
* 原始类,不加密
* @author 李亚杰
* @date 2024/4/16 16:52
* @description NoEncryption
*/
public class NoEncryption extends Encryption{
@Override
protected String encode(String s) {//具体实现类,不加密
return s;
}
}
/**
* 抽象修饰类
* @author 李亚杰
* @date 2024/4/16 16:54
* @description AbstractDecorationEncryption
*/
public abstract class AbstractDecorationEncryption extends Encryption{
protected Encryption encryption;
public AbstractDecorationEncryption(Encryption encryption){
this.encryption = encryption;
}
@Override
protected String encode(String s){
return encryption.encode(s);
}
}
/**
* 简单加密修饰类
* @author 李亚杰
* @date 2024/4/16 16:57
* @description EasyEncryption
*/
public class EasyEncryption extends AbstractDecorationEncryption{
public EasyEncryption(Encryption encryption) {
super(encryption);
}
@Override
protected String encode(String s) {
s = s+"-easy-";
return super.encode(s);
}
}
/**
* 中等加密修饰类
* @author 李亚杰
* @date 2024/4/16 16:58
* @description MediumEncryption
*/
public class MediumEncryption extends AbstractDecorationEncryption{
public MediumEncryption(Encryption encryption) {
super(encryption);
}
@Override
protected String encode(String s) {
s = s+"-medium-";
return super.encode(s);
}
}
/**
* 复杂加密修饰类
* @author 李亚杰
* @date 2024/4/16 17:01
* @description ComplexEncryption
*/
public class ComplexEncryption extends AbstractDecorationEncryption{
public ComplexEncryption(Encryption encryption) {
super(encryption);
}
@Override
protected String encode(String s) {
s = s+"-complex-";
return super.encode(s);
}
}
测试
/**
* @author 李亚杰
* @date 2024/4/16 17:05
* @description clint
*/
public class clint {
public static void main(String[] args) {
Encryption e1,e2,e3,e4;
e1 = new NoEncryption();
System.out.println(e1.encode("test"));
e2 = new EasyEncryption(e1);
System.out.println(e2.encode("test"));
e3 = new ComplexEncryption(e2);
System.out.println(e3.encode("test"));
e4 = new MediumEncryption(e3);
System.out.println(e4.encode("test"));
}
}
通过装饰类,实现了对文本的多次加密,并且能够通过选择不同的加密方式实现加密,新增加密方法时,只需要继承抽象修饰类并且重写加密方法即可,方便拓展。