装饰者模式
装饰模式(Decorator Pattern) :动态地给一个对象增加一些额外的职责(Responsibility),就增加对象功能来说,装饰模式比生成子类实现更为灵活。其别名也可以称为包装器(Wrapper),与适配器模式的别名相同,但它们适用于不同的场合。根据翻译的不同,装饰模式也有人称之为“油漆工模式”,它是一种对象结构型模式。
装饰模式包含如下角色:
• Component: 抽象构件
• ConcreteComponent: 具体构件(只管执行)
• Decorator: 抽象装饰类(实现具体构建的方法)
• ConcreteDecorator: 具体装饰类(调用父类构造器实例化)
装饰者模式多层加密
个人理解
感觉装饰者模式就是无限套娃,Component: 抽象构件会产生两个类,一个是具体的实现,一个是装饰品的抽象类,然后就是不同的装饰品继承这个抽象类。
具体的实现:继承接口(Cipher),创建这个原型(SimpleCipher),要被装饰的东西。
**抽象实现:**继承接口(Cipher),创建抽象类(CipherDecorator),通过构造方法传入(Cipher),然后调用Cipher的装饰方法。
**装饰类实现:**继承抽象实现,复写父类的方法 调用 + 装饰
例如:
public class AdvancedCipher extends CipherDecorator {
protected AdvancedCipher(Cipher cipher) {
super(cipher);
}
public String encrypt(String plainText) {
String result = super.encrypt(plainText);
result=mod(result);
return result;
}
public String mod(String text) {
String str="";
for(int i=0;i<text.length();i++){
String c=String.valueOf(text.charAt(i)%6);
str+=c;
}
return str;
}
}