java設計模式系列之裝飾者模式_java

來源:互聯網
上載者:User

何為裝飾者模式 (Decorator)?
動態地給一個對象添加一些額外的職責。就增加功能來說,Decorator 模式相比產生子類更為靈活。
一、結構

Component : 定義一個對象介面,可以給這些對象動態地添加職責。

interface Component {  public void operation();}ConcreteComponent : 實現 Component 定義的介面。class ConcreteComponent implements Component {  @Override  public void operation() {    System.out.println("初始行為");  }}

Decorator : 裝飾抽象類別,繼承了 Component, 從外類來擴充 Component 類的功能,但對於 Component 來說,是無需知道 Decorator 的存在的。

class Decorator implements Component {  // 持有一個 Component 對象,和 Component 形成彙總關係  protected Component component;    // 傳入要進一步修飾的對象  public Decorator(Component component) {    this.component = component;  }    @Override  // 調用要修飾對象的原方法  public void operation() {    component.operation();  }}

ConcreteDecorator : 具體的裝飾對象,起到給 Component 添加職責的功能。

class ConcreteDecoratorA extends Decorator {  private String addedState = "新屬性1";    public ConcreteDecoratorA(Component component) {    super(component);  }    public void operation() {    super.operation();    System.out.println("添加屬性: " + addedState);  }}class ConcreteDecoratorB extends Decorator {  public ConcreteDecoratorB(Component component) {    super(component);  }  public void operation() {    super.operation();    AddedBehavior();  }    public void AddedBehavior() {    System.out.println("添加行為");  }}

測試代碼

public class DecoratorPattern {  public static void main(String[] args) {    Component component = new ConcreteComponent();    component.operation();        System.out.println("======================================");    Decorator decoratorA = new ConcreteDecoratorA(component);    decoratorA.operation();        System.out.println("======================================");    Decorator decoratorB = new ConcreteDecoratorB(decoratorA);    decoratorB.operation();  }}

運行結果

初始行為======================================初始行為添加屬性: 新屬性1======================================初始行為添加屬性: 新屬性1添加行為

 二、應用情境

1、需要動態、透明的為一個對象添加職責,即不影響其他對象。
2、需要動態給一個對象添加功能,這些功能可以再動態撤銷。
3、需要增加由一些準系統的排列組合而產生的非常大量的功能,從而使繼承關係變的不現實。
4、當不能採用產生子類的方法進行擴充時。一種情況是,可能有大量獨立的擴充,為支援每一種組合將產生大量的子類,使得子類數目呈爆炸性增長。另一種情況可能是因為類定義被隱藏,或類定義不能用於產生子類。

三、要點

1、裝飾對象和真實對象有相同的介面。這樣用戶端對象就能以和真實對象相同的方式和裝飾對象互動。

2、裝飾對象包含一個真實對象的引用(reference)。

3、裝飾對象接受所有來自用戶端的請求。它把這些請求轉寄給真實的對象。

4、裝飾對象可以在轉寄這些請求以前或以後增加一些附加功能。這樣就確保了在運行時,不用修改給定對象的結構就可以在外部增加附加的功能。在物件導向的設計中,通常是通過繼承來實現對給定類的功能擴充。

以上就是關於java裝飾者模式的相關內容介紹,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.