Java资源网

| JAVA基础 | 环境配置 | JDBC | 线程技术 | Socket编程 | JavaMail | JAVA与XML | 设计模式 | 技术新闻 | Java认证 | 程序人生 软件下载
| JSP&Servlet | Spring | Struts | Hibernate | JBuilder | Eclipse | WebService | EJB技术 | J2ME开发 | 应用服务器 | JXTA | Ajax
Articles search文章搜索
   关键字:
   类 别:
       
New download 最新下载
· [组件]HTML Parser 1.5
· [教程]WebSphere Studio应用教程
· [组件]JDom 1.0
· [工具]Junit3.8.1
· [教程]EJB编程及J2EE系统架构和设计
· [教程]EJB教程
· [教程]J2EE Tutorial中文版
· [教程]Java编程思想2(英文)
· [教程]java编程思想(完整版)
· [教程]Java网络编程
New articles 最新文章
· 设计移动 Web 服务
· 解析XML的时候完全忽略DTD
· 理解XML Schema XML Schema 初步
· 标签库的深入研究
· 提升JSP应用程序的七大绝招
· 如何使用JDOM对XML文件进行操作
· 处理XML字符串中特殊字符
· 利用Digester把XML转换成为Java对象
· 使用WebService 和RMI远程协作
· 使用Axis开发Web Service程序
Articles top 热门文章
· Eclipse基础--plugin插件安装(6644)
· eclipse+tomcat+lomboz的安装配置说明(4774)
· Java程序员就业前景(4584)
· Windows下JAVA环境变量的设置祥解(3788)
· Tomcat下JSP、Servlet和JavaBean环境的配置(3716)
· 使用links方式安装Eclipse插件(3698)
· 一个老程序员的心理话(3533)
· linux下jdk的安装与配置(3459)
· 初学者入门:Structs中基本配置入门(3334)
· Eclipse 运行命令行参数大全(3084)
您的位置:首页>>设计模式>>[Structuralnbsp;Patterns]nbsp;Thenbsp;Decoratornbsp;Pattern
[Structuralnbsp;Patterns]nbsp;Thenbsp;Decoratornbsp;Pattern
2007-04-13   来源:www.javaresearch.org  作者:未知

Intent


The Decorator pattern provides us a flexible alternative to subclassing for extending functionality without having to create a new derived class. In a nutshell, it lets you attach responsibilities to objects at runtime.

Motivation


You want to add behavior or state to individual objects at run-time. Inheritance is not feasible because it is static and applies to an entire class. For example, consider going down to the local coffee shop, BeanMeUp, for a coffee. There are typically many different drinks on offer -- espressos, lattes, teas, iced coffees, hot chocolate to name a few, as well as a number of extras (which cost extra too) such as whipped cream or an extra shot of espresso. You can also make certain changes to your drink at no extra cost, such as asking for decaf coffee instead of regular coffee. If you want to describe a plain cappuccino, you create it with 

new Espresso(new FoamedMilk(new Mug()))
Creating a decaf Café Mocha with whipped cream requires an even longer description. 

Structure




Steps are as follows:
1. Create a "lowest common denominator" that makes classes interchangeable
2. Create a second level base class for optional functionality
3. "Core" class and "Decorator" class declare an "isa" relationship
4. Decorator class "hasa" instance of the "lowest common denominator"
5. Decorator class delegates to the "hasa" object
6. Create a Decorator derived class for each optional embellishment
7. Decorator derived classes delegate to base class AND add extra stuf
8. Client has the responsibility to compose desired configurations

Here, as the previous chapter metioned, you want to avoid changing visitor interface while adding a new Visitable object. We are prone to decrating visitor interface. Then All other visit() methods can be added later as point-to-point coupling is required.

Code's snapshot:

  1. abstract class DetractorVisitor {
  2.   abstract public void visit( Object o );
  3.   public void visitTheOther( TheOther e ) {
  4.     System.out.println( "DetractorVisitor: do Base on " + e.theOther() );
  5.   }
  6.   // 1. Look for visitElementClassName() in the current class
  7.   // 2. Look for visitElementClassName() in superclasses
  8.   // 3. Look for visitElementClassName() in interfaces
  9.   // 4. Look for visitObject() in current class
  10.   protected Method getMethod( Class c ) {
  11.     Class  newc = c;
  12.     Method m    = null;
  13.     while (m == null  &&  newc != Object.class) {
  14.       String method = newc.getName();
  15.       method = "visit" + method.substring( method.lastIndexOf('.') + 1 );
  16.       try {
  17.         m = getClass().getMethod( method, new Class[] { newc } );
  18.       } catch (NoSuchMethodException ex) {
  19.         newc = newc.getSuperclass();
  20.     } }
  21.     if (newc == Object.class) {
  22.       // System.out.println( "Searching for interfaces" );
  23.       Class[] interfaces = c.getInterfaces();
  24.       for (int i=0; i < interfaces.length; i++) {
  25.         String method = interfaces[i].getName();
  26.         method = "visit" + method.substring( method.lastIndexOf('.') + 1 );
  27.         try {
  28.           m = getClass().getMethod( method, new Class[] { interfaces[i] } );
  29.         } catch (NoSuchMethodException ex) { }
  30.     } }
  31.     if (m == null)
  32.       try {
  33.         m = getClass().getMethod( "visitObject"new Class[] { Object.class } );
  34.       } catch (Exception ex) { }
  35.     return m;
  36. } }
  37. class UpVisitor extends DetractorVisitor {
  38.   public void visit( Object o ) {
  39.     try {
  40.       getMethod( o.getClass() ).invoke( thisnew Object[] { o } );
  41.     } catch (Exception ex) {
  42.       System.out.println( "UpVisitor - no appropriate visit() method" );
  43.   } }
  44.   public void visitThis( This e ) {
  45.     System.out.println( "UpVisitor: do Up on " + e.thiss() );
  46.   }
  47.   public void visitObject( Object e ) {
  48.     System.out.println( "UpVisitor: generic visitObject() method" );
  49. } }
  50. class DownVisitor extends DetractorVisitor {
  51.   public void visit( Object o ) {
  52.     try {
  53.       getMethod( o.getClass() ).invoke( thisnew Object[] { o } );
  54.     } catch (Exception ex) {
  55.       System.out.println( "DownVisitor - no appropriate visit() method" );
  56.   } }
  57.   public void visitThat( That e ) {
  58.     System.out.println( "DownVisitor: do Down on " + e.that() );
  59. } }
  60. class VisitorDemo {
  61.   public static void main( String[] args ) {
  62.     Element[]    list = { new This(), new That(), new TheOther() };
  63.     UpVisitor    up   = new UpVisitor();
  64.     DownVisitor  down = new DownVisitor();
  65.     for (int i=0; i < list.length; i++)
  66.       list[i].accept( up );
  67.     for (int i=0; i < list.length; i++)
  68.       list[i].accept( down );
  69. } }

// UpVisitor: do Up on This
// UpVisitor: generic visitObject() method
// DetractorVisitor: do Base on TheOther
// DownVisitor - no appropriate visit() method
// DownVisitor: do Down on That
// DetractorVisitor: do Base on TheOther

Example


It is essentially an abstract class that doesn’t do any processing, but provides a layer where the relevant methods have been duplicated. It normally forwards these method calls to the enclosed parent stream class. So let's go over the java.io classes, the FilterInputStream class is thus a Decorator that can be wrapped around any input stream class. 

  --相关文章--
· 面向对象编程,我的思想 (2007-04-13)
· 面向对象的思维方式 (2007-04-13)
· 通过Javanbsp;Swing看透MVC设计模式 (2007-04-13)
· 适配器模式(Adapternbsp;Pattern) (2007-04-13)
· 追MM与Java的23种设计模式 (2007-04-13)
· 责任链模式(Chainnbsp;ofnbsp;Responsibility) (2007-04-13)

版权所有©2005-2006 JAVA资源网 渝ICP备05007591号 虚拟主机 | 关于我们 | 联系方式 | 广告业务 | 网站地图 | 友情链接