Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1277691
  • 博文数量: 185
  • 博客积分: 50
  • 博客等级: 民兵
  • 技术积分: 3934
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-11 13:11
个人简介

iihero@ChinaUnix, ehero.[iihero] 数据库技术的痴迷爱好者. 您可以通过iihero AT qq.com联系到我 以下是我的三本图书: Sybase ASE in Action, Oracle Spatial及OCI高级编程, Java2网络协议内幕

文章分类

全部博文(185)

文章存档

2014年(4)

2013年(181)

分类: Java

2013-07-25 10:00:44

概述

动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。可以简称为"修修补补"


适用性

  • 1.在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
  • 2.处理那些可以撤消的职责。
  • 3.当不能采用生成子类的方法进行扩充时。

参与者

  • 1.Component 定义一个对象接口,可以给这些对象动态地添加职责。 
  • 2.ConcreteComponent 定义一个对象,可以给这个对象添加一些职责。 
  • 3.Decorator 维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。 
  • 4.ConcreteDecorator 向组件添加职责。

其基本类图如下图所示:


示例:



  1. package com.sql9.structured;  
  2.   
  3.   
  4. abstract class Component {  
  5.     public abstract void draw();  
  6. }  
  7.   
  8. class ConcreteComponent extends Component {  
  9.       
  10.     private String name;  
  11.       
  12.     public ConcreteComponent(String name) {  
  13.         this.name = name;  
  14.     }  
  15.   
  16.     @Override  
  17.     public void draw() {  
  18.         System.out.println(String.format("ConcreteComponent - %s", name));  
  19.     }  
  20.       
  21. }  
  22.   
  23. abstract class Decorator extends Component {  
  24.     protected Component internalComponent;  
  25.       
  26.     public void setComponent(Component c) {  
  27.         this.internalComponent = c;  
  28.     }  
  29.       
  30.     @Override  
  31.     public void draw() {  
  32.         if (internalComponent != null) {  
  33.             internalComponent.draw();  
  34.         }  
  35.     }  
  36. }  
  37.   
  38. class ConcreteDecorator extends Decorator {  
  39.       
  40.     private String customName;  
  41.       
  42.     public ConcreteDecorator(String name) {  
  43.         this.customName = name;  
  44.     }  
  45.       
  46.     @Override  
  47.     public void draw() {  
  48.         extraDraw();  
  49.         super.draw();  
  50.     }  
  51.       
  52.     protected void extraDraw() {  
  53.         System.out.println("Draw extra action in ConcreteDecorator...");  
  54.     }  
  55. }  
  56.   
  57.   
  58. public class DecoratorTest {  
  59.   
  60.     public static void main(String[] args) {  
  61.         ConcreteComponent c = new ConcreteComponent("This is the real component");  
  62.         ConcreteDecorator d = new ConcreteDecorator("This is a decorator for the component");  
  63.         d.setComponent(c);  
  64.         d.draw();  
  65.     }  
  66. }  

结果:



Draw extra action in ConcreteDecorator...
ConcreteComponent - This is the real component

阅读(1585) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~