设计模式 之 创建型模式 <四> 装饰模式(Decorator Pattern ) -- 扩展系统功能
角色:
● Component(抽象构件):它是具体构件和抽象装饰类的共同父类,声明了在具体构件中实 现的业务方法,
它的引入可以使客户端以一致的方式处理未被装饰的对象以及装饰之后的对 象,实现客户端的透明操作。
● ConcreteComponent(具体构件):它是抽象构件类的子类,用于定义具体的构件对象,实 现了在抽象构件中声明的方法,装饰器可以给它增加额外的职责(方法)。
● Decorator(抽象装饰类):它也是抽象构件类的子类,用于给具体构件增加职责,但是具体 职责在其子类中实现。它维护一个指向抽象构件对象的引用,
通过该引用可以调用装饰之前 构件对象的方法,并通过其子类扩展该方法,以达到装饰的目的。
● ConcreteDecorator(具体装饰类):它是抽象装饰类的子类,负责向构件添加新的职责。
每 一个具体装饰类都定义了一些新的行为,它可以调用在抽象装饰类中定义的方法,并可以增 加新的方法用以扩充对象的行为。
练习
Sunny软件公司欲开发了一个数据加密模块,可以对字符串进行加密。最简单的加密算法 通过对字母进行移位来实现,同时还提供了稍复杂的逆向输出加密,
还提供了更为高级 的求模加密。用户先使用最简单的加密算法对字符串进行加密,如果觉得还不够可以对 加密之后的结果使用其他加密算法进行二次加密,
当然也可以进行第三次加密。试使用 装饰模式设计该多重加密系统。
Component(抽象构件)
1 //Component(抽象构件) 2 public abstract class DataEncryption { 3 public abstract int encryption(int data); 4 }
ConcreteComponent(具体构件)
1 //ConcreteComponent(具体构件) 2 public class EncryptionModule extends DataEncryption { 3 String TAG="decorator"; 4 @Override 5 public int encryption(int data) { 6 int result=data>>2; 7 Log.e(TAG,"对数据"+data+"进行移位运输得到:"+result); 8 return result; 9 } 10 11 }
Decorator(抽象装饰类)
1 //ecorator(抽象装饰类) 2 public class DataEncryptionDecorator extends DataEncryption { 3 protected DataEncryption dataEncryption; 4 public DataEncryptionDecorator(DataEncryption dataEncryption){ 5 this.dataEncryption=dataEncryption; 6 } 7 @Override 8 public int encryption(int data) { 9 return dataEncryption.encryption(data); 10 } 11 }
ConcreteDecorator(具体装饰类)
1 //ConcreteDecorator(具体装饰类) 2 public class ModularEncryptionDecorator extends DataEncryptionDecorator { 3 String TAG="decorator"; 4 public ModularEncryptionDecorator(DataEncryption dataEncryption) { 5 super(dataEncryption); 6 } 7 8 @Override 9 public int encryption(int data) { 10 data= super.encryption(data); 11 int result=data%100000; 12 Log.e(TAG,"对数据"+data+"进行取模运输得到:"+result); 13 return result; 14 } 15 }
ConcreteDecorator(具体装饰类)
1 //ConcreteDecorator(具体装饰类) 2 public class ReverseOutputEncryptionDecorator extends DataEncryptionDecorator { 3 String TAG="decorator"; 4 public ReverseOutputEncryptionDecorator(DataEncryption dataEncryption) { 5 super(dataEncryption); 6 } 7 8 @Override 9 public int encryption(int data) { 10 data= super.encryption(data); 11 int result=reverse(data); 12 Log.e(TAG,"对数据"+data+"进行反相输出得到:"+result); 13 return result; 14 } 15 16 private int reverse(int data){ 17 String temp=String.valueOf(data); 18 byte[] bytes=temp.getBytes(); 19 byte[] tempbyte=new byte[bytes.length]; 20 for(int k=0;k<temp.length();k++){ 21 tempbyte[k]=bytes[tempbyte.length-k-1]; 22 } 23 return Integer.parseInt(new String(tempbyte)); 24 } 25 }