到 Google 资讯主页   
EasyJF首页   资料   源码   软件    论坛   网站    
   使用帮助    
    该信息为本站MyRSS系统缓存内容,部分图片及附件有可能无法正常使用.easyjf.comwww.javaresearch.org无关,不对该信息负责.通过http://www.javaresearch.org/article//showarticle.jsp?column=31&thread=541访问该信息的原始内容.
页面功能  【加入收藏】 【推荐给朋友】 【字体:  】 【关闭】   
[Structural Patterns] The Decorator Pattern
作者:Bryan Lau 来源:www.javaresearch.org  发布时间:2006-02-28 12:43:37.477


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. 

 
相关文章
 
页面功能  【加入收藏】 【推荐给朋友】 【字体:  】 【关闭】   


EasyJF.com 2006 隐私政策 使用EasyJF前必读