中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > 编程语言 > Java > 设计模式
[Structural Patterns] The Decorator Pattern
作者:未知 时间:2005-07-24 21:23 出处:JR 责编:chinaitpower
              摘要:[Structural Patterns] The Decorator Pattern

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. 
关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有