1. 程式人生 > >java之裝飾器模式

java之裝飾器模式

args pattern lte auto eight pro 簡單的 add con

Decorator Pattern(裝飾器模式),定義:Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.(動態地給一個對象添加一些額外的職責。就增加功能來說,裝飾模式相比生成子類更為靈活)

裝飾器的通用視圖:

技術分享

上圖四個角色解釋一下:

1.Component抽象構件:

Component是一個接口或者一個抽象類,就是定義我們最核心的對象,也就是最原始的對象,最高層次的抽象,統一整個裝飾器系統,用於裝飾器之間溝通的橋梁,就像II/O流中的InputStream,OutputStream一樣

2.ConcreteComponent具體構件

ConcreteComponent是最核心,最原始,最基本的接口或者抽象類的實現,你要裝飾的就是它,裝飾的源頭,你裝飾的最底層,就像I/O流一樣,這就直接跟底層打交道的節點流,就比如FileInputStream

3.Decorator 裝飾角色

一般是一個抽象類,實現接口或者抽象方法,它並不一定有抽象方法,但在它的屬性裏必須有一個private變量指向Component抽象構件,一般是用構造器初始化。就像I/O流中的FilterInputStream

4.ConcreteDecoratorA,ConcreteDecoratorB具體的裝飾器角色,這就是要將我們之間建的最核心,最原始,最基礎的東西裝飾成東西或者其他的東西,就像I/O中的BufferedInputStream,DataInputStream等。

下面給出一個簡單的例子:

  1 package decorator;
  2 //抽象構件
  3 public interface Component
  4 {
  5     void operation();
  6 }
  7 //具體的抽象構件的實現
  8 public class ConcreteComponent implements Component
  9 {
 10 
 11     /** { @inheritDoc } */
 12     @Override
 13     public void operation()
 14     {
 15         System.out.println("我是ConcreteComponent,是最原始的實現類,我處於最底層");
16 } 17 18 } 19 //抽象裝飾器 20 public abstract class Decorator implements Component 21 { 22 private Component component; 23 24 /** 25 * @param component 26 */ 27 public Decorator(Component component) 28 { 29 this.component = component; 30 } 31 32 /** { @inheritDoc } */ 33 @Override 34 public void operation() 35 { 36 component.operation(); 37 } 38 } 39 //具體裝飾器A 40 public class ConcreteDecoratorA extends Decorator 41 { 42 43 /** 44 * @param component 45 */ 46 public ConcreteDecoratorA(Component component) 47 { 48 super(component); 49 } 50 51 public void methodA() 52 { 53 System.out.println("我是ConcreteDecoratorA,添加的新功能"); 54 } 55 56 /** { @inheritDoc } */ 57 @Override 58 public void operation() 59 { 60 methodA(); 61 super.operation(); 62 System.out.println("ConcreteDecoratorA的operation執行完畢"); 63 } 64 65 } 66 //具體裝飾器B 67 public class ConcreteDecoratorB extends Decorator 68 { 69 70 /** 71 * @param component 72 */ 73 public ConcreteDecoratorB(Component component) 74 { 75 super(component); 76 } 77 78 public void methodB() 79 { 80 System.out.println("我是ConcreteDecoratorB,添加的新功能"); 81 } 82 83 /** { @inheritDoc } */ 84 @Override 85 public void operation() 86 { 87 methodB(); 88 super.operation(); 89 System.out.println("ConcreteDecoratorB的operation執行完畢"); 90 } 91 92 } 93 //測試類 94 public class Demo 95 { 96 public static void main(String[] args) 97 { 98 Component component = new ConcreteComponent(); 99 100 ConcreteDecoratorB decoratorB = new ConcreteDecoratorB(new ConcreteDecoratorA(component)); 101 102 decoratorB.operation(); 103 } 104 }

java之裝飾器模式