設計模式之裝飾者模式(Decorator Pattern)

模式分析:

        動態地給一個對象添加一些額外的職責。就增長功能來講, Decorator模式相比生成子類更爲靈活。該模式以對客 戶端透明的方式擴展對象的功能。html

使用情景:

  • 在不影響其餘對象的狀況下,以動態、透明的方式給單個對象添加職責。
  • 處理那些能夠撤消的職責。
  • 當不能採用生成子類的方法進行擴充時。一種狀況是,可能有大量獨立的擴展,爲支持每一種組合將產生大量的 子類,使得子類數目呈爆炸性增加。另外一種狀況多是由於類定義被隱藏,或類定義不能用於生成子類。

角色分析:

  1. Component(被裝飾對象的基類):定義一個對象接口,能夠給這些對象動態地添加職責。
  2. ConcreteComponent(具體被裝飾對象):定義一個對象,能夠給這個對象添加一些職責。
  3. Decorator(裝飾者抽象類)維持一個指向Component實例的引用,並定義一個與Component接口一致的接口。
  4. ConcreteDecorator(具體裝飾者):具體的裝飾對象,給內部持有的具體被裝飾對象,增長具體的職責。

類圖:

demo:

//component 
public interface Person {

    void eat();
}

//
public class Man implements Person {

    public void eat() {
        System.out.println("男人在吃");
    }
}
//
public abstract class Decorator implements Person {

    protected Person person;
    
    public void setPerson(Person person) {
        this.person = person;
    }
    
    public void eat() {
        person.eat();
    }
}
//
public class ManDecoratorA extends Decorator {

    public void eat() {
        super.eat();
        reEat();
        System.out.println("ManDecoratorA類");
    }

    public void reEat() {
        System.out.println("再吃一頓飯");
    }
}
public class ManDecoratorB extends Decorator {
    
    public void eat() {
        super.eat();
        System.out.println("===============");
        System.out.println("ManDecoratorB類");
    }
}

public static void main(String[] args) {

        Man man = new Man();
        ManDecoratorA a = new ManDecoratorA();
        ManDecoratorB b = new ManDecoratorB();
        a.setPerson(man);
        b.setPerson(man);

        a.eat();
        b.eat();

}

總結:

  • OO原則:動態地將責任附加到對象上。想要擴展功能, 裝飾者提供有別於繼承的另外一種選擇。
  • 除了繼承,裝飾者模式也能夠讓咱們擴展行爲。
  • 裝飾者能夠在被裝飾者的行爲前面與/或後面加上本身的行爲,甚至將被裝飾者的行爲整個取代掉,而達到特定的目的。
  • 能夠有無數個裝飾者包裝一個組件。
  • 裝飾者通常對組建的客戶是透明的,除非客戶程序依賴於組件的具體類型。

參考文檔java

相關文章
相關標籤/搜索