|
| [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:
-
- abstract class DetractorVisitor {
- abstract public void visit( Object o );
-
- public void visitTheOther( TheOther e ) {
- System.out.println( "DetractorVisitor: do Base on " + e.theOther() );
- }
-
- // 1. Look for visitElementClassName() in the current class
- // 2. Look for visitElementClassName() in superclasses
- // 3. Look for visitElementClassName() in interfaces
- // 4. Look for visitObject() in current class
- protected Method getMethod( Class c ) {
- Class newc = c;
- Method m = null;
- while (m == null && newc != Object.class) {
- String method = newc.getName();
- method = "visit" + method.substring( method.lastIndexOf('.') + 1 );
- try {
- m = getClass().getMethod( method, new Class[] { newc } );
- } catch (NoSuchMethodException ex) {
- newc = newc.getSuperclass();
- } }
- if (newc == Object.class) {
- // System.out.println( "Searching for interfaces" );
- Class[] interfaces = c.getInterfaces();
- for (int i=0; i < interfaces.length; i++) {
- String method = interfaces[i].getName();
- method = "visit" + method.substring( method.lastIndexOf('.') + 1 );
- try {
- m = getClass().getMethod( method, new Class[] { interfaces[i] } );
- } catch (NoSuchMethodException ex) { }
- } }
- if (m == null)
- try {
- m = getClass().getMethod( "visitObject", new Class[] { Object.class } );
- } catch (Exception ex) { }
- return m;
- } }
-
- class UpVisitor extends DetractorVisitor {
- public void visit( Object o ) {
- try {
- getMethod( o.getClass() ).invoke( this, new Object[] { o } );
- } catch (Exception ex) {
- System.out.println( "UpVisitor - no appropriate visit() method" );
- } }
- public void visitThis( This e ) {
- System.out.println( "UpVisitor: do Up on " + e.thiss() );
- }
- public void visitObject( Object e ) {
- System.out.println( "UpVisitor: generic visitObject() method" );
- } }
-
- class DownVisitor extends DetractorVisitor {
- public void visit( Object o ) {
- try {
- getMethod( o.getClass() ).invoke( this, new Object[] { o } );
- } catch (Exception ex) {
- System.out.println( "DownVisitor - no appropriate visit() method" );
- } }
- public void visitThat( That e ) {
- System.out.println( "DownVisitor: do Down on " + e.that() );
- } }
-
-
- class VisitorDemo {
- public static void main( String[] args ) {
- Element[] list = { new This(), new That(), new TheOther() };
- UpVisitor up = new UpVisitor();
- DownVisitor down = new DownVisitor();
- for (int i=0; i < list.length; i++)
- list[i].accept( up );
- for (int i=0; i < list.length; i++)
- list[i].accept( down );
- } }
// 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.
|
|
|