java设计模式---------装饰模式

JAVA23种设计模式之一,英文叫Decorator Pattern。装饰模式是在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。

 

编辑本段装饰模式的特点

  (1) 装饰对象和真实对象有相同的接口。这样客户端对象就可以以和真实对象相同的方式和装饰对象交互。

 

  (2) 装饰对象包含一个真实对象的索引(reference)

 

  (3) 装饰对象接受所有的来自客户端的请求。它把这些请求转发给真实的对象。

 

  (4) 装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。

 

编辑本段代码示例

  以下示例中,ThirdParty.Java假定是一个现有的或者第三方的功能,因某种原因我们不能直接修改,它提供了一个sayMsg()的方法,而我们现在要做的是想在它的sayMsg()方法中增加一些我们想额外输出的内容,于是我们重写了一个Decorator.java类。MailTest.java是客户端测试程序。

 

  ThirdParty.Java

 

  =====================

 

  package decorator.saystr;

 

  public interface ThirdParty {

 

  public String sayMsg();

 

  }

 

  Decorator.java

 

  ==================

 

  package decorator.saystr;

 

  public class Decorator implements ThirdParty {

 

  privateThirdParty thirdParty;

 

  public Decorator(ThirdParty thirdParty){

 

  this.thirdParty= thirdParty;

 

  }

 

  publicString say(){

 

  return"##"+ thirdParty.sayMsg() + "##";

 

  }

 

  }

 

  MailTest.java

 

  ====================

 

  package decorator.saystr;

 

  public class MailTest {

 

  public static void main(String[] args){

 

  ThirdParty thirdPartyOne = newThirdPartyOne();

 

  Decorator decorator1 = newDecorator(thirdPartyOne);

 

  System.out.println(decorator1.say());

 

  ThirdParty thirdPartyTwo = newThirdPartyTwo();

 

  Decorator decorator2 = newDecorator(thirdPartyTwo);

 

  System.out.println(decorator2.say());

 

  }

 

  }

posted @ 2012-04-25 15:59  到是非得失  阅读(227)  评论(0编辑  收藏  举报