???? 裝飾模式:動態地給一個對象添加一些額外的職責。就增加功能來說,Decorator(裝飾)模式相比生成子類更為靈活。
???適用環境:
  • 在不影響其他對象的情況下,以動態、透明的方式給單個對象添加職責。
  • 處理那些可以撤消的職責。
  • 當不能采用生成子類的方法進行擴充時。一種情況是,可能有大量獨立的擴展,為支持每一種組合將產生大量的子類,使得子類數目呈爆炸性增長。另一種情況可能是因為類定義被隱藏,或類定義不能用于生成子類。

    本模式中包含的角色:
    抽象構件(Component):給出一個抽象接口,以規范準備接收附加責任的對象。
    具體構件(Concrete Component):定義一個接收到附加責任的類。
    裝飾(Decorator):持有一個構件對象的實例,并定義與抽象構件一致的接口。
    具體裝飾(Concrete Decorator):負責給構件對象貼上附加的責任。
    UML圖如下:
    Decorator.jpg

    具體例子:
    先定義抽象構件:

    package?decorator;
    //抽象構件接口
    public?interface?Component{
    ????
    public?void?sampleOperation();
    }

    一個具體構件----門:
    package?decorator;
    //具體構件-----門
    public?class??Door?implements?Component{
    ????
    //實現方法
    ????public?void?sampleOperation(){
    ????????System.out.println(
    "build?a?door");
    ????}

    }

  • 裝飾(抽象類):
    package?decorator;

    public?abstract?class?Decorator?implements?Component{
    ????
    //持有一個構件對象的實例
    ????private?Component?component;
    ????
    //構造方法
    ????public?Decorator(Component?component){
    ????????
    this.component=component;
    ????}

    ????
    //方法的具體實現
    ????public??void?sampleOperation(){
    ????????component.sampleOperation();
    ????}

    }

    具體裝飾:
    package?decorator;
    //具體裝飾----把手
    public?class?Knob?extends?Decorator{

    ????
    public?Knob(Component?component){
    ????????
    super(component);
    ????}

    ????
    ????
    public?void?sampleOperation(){
    ????????
    super.sampleOperation();
    ????????
    //附加的"責任"
    ????????System.out.println("add?a?knob");
    ????}

    }
    package?decorator;
    //具體裝飾----鎖
    public?class?Lock?extends?Decorator{

    ????
    public?Lock(Component?component){
    ????????
    super(component);
    ????}

    ????
    public?void?sampleOperation(){
    ????????
    super.sampleOperation();
    ????????
    //附加"責任"
    ????????System.out.println("add?a?lock");
    ????}

    }
    運行類:
    package?decorator;

    public?class?DecoratorPattern{
    ????
    public?static?void?main(String[]?args){
    ????????Component?door
    =new?Door();
    ????????Component?lock
    =new?Lock(door);
    ????????Component?knob
    =new?Knob(lock);
    ????????knob.sampleOperation();
    ????}

    }

    運行結果:
    build a door
    add a lock
    add a knob
    Press any key to continue...

    Java 的I/O API就是使用本模式實現的
    ,I/O變種很多,如果都采取繼承方法,將會產生很多子類,顯然相當繁瑣.

    裝飾模式與適配器模式的區別與聯系:
    ???這兩種模式都有一個別名Wrapper模式,兩者的區別:適配器模式的用意是改變所考慮對象的接口,而不一定要改變接口的性能,裝飾模式的用意是要保持接口,從而增強所考慮對象的性能。
    ?

    參考資料:http://blog.csdn.net/qutr/archive/2006/02/27/610788.aspx
    http://www.jdon.com/designpatterns/decorator.htm
    《Java與模式》
    《設計模式速查手冊》