設計模式之裝飾模式

裝飾模式

裝飾模式又稱包裝器Wrapper,它描述瞭如何動態地爲對象添加職責。裝飾模式是一種結構型模式,這一模式採用遞歸方式組合對象,從而允許你添加任意多的對象職責。裝飾模式以對客戶端透明的方式擴展對象的功能,是繼承關係的一個替代方案,實際上Java 的I/O API就是使用裝飾模式實現的。

定義
動態地給一個對象添加一些額外的職責,就增加功能來說,裝飾模式相比生成子類更爲靈活。

使用場景

  1. 在不影響其他對象的情況下,以動態、透明的方式給單個對象添加職責。

  2. 處理那些可以撤銷的職責。

  3. 當不能採用生成子類的方法進行擴充時,一種情況是,可能有大量的獨立地擴展,爲支持每一種組合將產生大量的子類,使得子類數目呈爆炸性增長。另一種情況可能是因爲類的定義被隱藏,或類定義不能用於生成子類。

結構
裝飾模式結構圖

實現
Component接口與具體實現

public interface Component {

    void operation();

}

public class ConcreteComponent implements Component {

    public void operation() {
        System.out.println("ConcreteComponent's operation");
    }

}

Decorator類與具體實現

public class Decorator implements Component{

    private Component component;

    public Decorator(Component component){
        this.component = component;
    }

    public void operation() {
        component.operation();
    }

}

public class ConcreteDecoratorA extends Decorator {

    public ConcreteDecoratorA(Component component) {
        super(component);
    }

    public void operation() {
        super.operation();
        System.out.println("ConcreteDecoratorA's operation");
    }

}

public class ConcreteDecoratorB extends Decorator {

    public ConcreteDecoratorB(Component component) {
        super(component);
    }

    public void operation() {
        super.operation();
        System.out.println("ConcreteDecoratorB's operation");
    }

}

裝飾模式比靜態繼承更靈活,比如要增加一個新的特性,裝飾模式只要多一個Decorator的實現即可,可以避免層次結構高層的類有太多的特性,有種“即用即付”的感覺。但是過多的使用裝飾模式會導致系統中有很多相似的對象,不易排錯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章