先看装饰模式的UML结构图:
再看看结构图中各个构建的解释:
什么是装饰模式:
接下来看看装饰模式的代码实现:
Component模拟:
package com.sjmx.decorator.first; /** * 密文接口 * @author LENOVO * */ public interface Cipher { public String encrypt(String plainText); }
具体对象:
package com.sjmx.decorator.first; /** * 密文接口实现类 * @author LENOVO * */ public class SimpleCipher implements Cipher { public String encrypt(String plainText) { String str=""; for(int i=0;i<plainText.length();i++) { char c=plainText.charAt(i); if(c>='a'&&c<='z') { c+=6; if(c>'z') c-=26; if(c<'a') c+=26; } if(c>='A'&&c<='Z') { c+=6; if(c>'Z') c-=26; if(c<'A') c+=26; } str+=c; } return str; } }
Decorator抽象类模拟:
package com.sjmx.decorator.first; /** * 密文装饰者 * * @author LENOVO * */ public abstract class CipherDecorator implements Cipher { private Cipher cipher; public CipherDecorator(Cipher cipher) { this.cipher = cipher; } public String encrypt(String plainText) { return cipher.encrypt(plainText); } }
装饰类的具体实现A:
package com.sjmx.decorator.first; /** * 复杂加密装饰者 * @author LENOVO * */ public class ComplexCipher extends CipherDecorator { public ComplexCipher(Cipher cipher) { super(cipher); } public String encrypt(String plainText) { String result=super.encrypt(plainText); result= this.reverse(result); return result; } public String reverse(String text) { String str=""; for(int i=text.length();i>0;i--) { str+=text.substring(i-1,i); } return str; } }
装饰类的具体实现B:
package com.sjmx.decorator.first; /** * 先进加密装饰者 * @author LENOVO * */ public class AdvancedCipher extends CipherDecorator { public 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; } }
客户端:
package com.sjmx.decorator.first; public class Client { public static void main(String args[]) { String password="jad2008"; //明文 String cpassword; //密文 Cipher sc,ac,cc; sc=new SimpleCipher(); cpassword=sc.encrypt(password); System.out.println(cpassword); System.out.println("---------------------"); cc=new ComplexCipher(sc); cpassword=cc.encrypt(password); System.out.println(cpassword); System.out.println("---------------------"); ac=new AdvancedCipher(cc); cpassword=ac.encrypt(password); System.out.println(cpassword); System.out.println("---------------------"); } }
运行结构:
各位可以简单的把代码运行一下看看,在(《大话设计模式》——读后感 (2)穿什么有这么重要?装饰模式之理解实例(2))中会加入自己的代码,并分享自己的体会