《Java與模式》學習筆記之三—–裝飾(Decorator)模式

來源:互聯網
上載者:User

    裝飾模式又稱封裝(Wrapper)模式,是以對用戶端透明的方式擴充項物件的功能,是繼承關係的一個替代方案。對用戶端透明意味著介面不變。

問題:

在OO設計和開發過程中, 經常會遇到下面的情況: 我們需要為已經設計好的類添加新的職責, 通常情況下我們會定義一個新類繼承自訂好的類. 由於組合比繼承更好(複雜度高,繼承深度深等原因, 見<設計模式解析>P39討論), 今天我們就來介紹一下應用的組合的裝飾模式.

類圖:

 

 

原始碼:

package com.designpatterns.decorator;

 

/**

 * 抽象介面,規範準備接收附加責任的對象

 * @author suki

 */

public interface Component {

       void operation();

}

 

/**

 * 接收附加責任, 此類型的類可以有多個, 只對應一個Decorator類

 * @author suki

 */

public class ConcreteComponent implements Component{

       public ConcreteComponent(){}

       public void operation()

       {

              System.out.println("ConcreteComponent.operation()");

       }

}

 

/**

 * 裝飾角色,持有一個構件(Component)對象的執行個體,並定義一個與抽象構件介面一致的介面

 * @author suki

 */

public class Decorator implements Component {

       private Component component;

      

       public Decorator(){}

      

       public Decorator(Component component)

       {

              this.component = component;

       }

      

       public void operation() {

              component.operation();

       }

}

 

/**

 * 添加附加責任

 * @author suki

 */

public class ConcreteDecorator extends Decorator {

       public ConcreteDecorator(){}

       public ConcreteDecorator(Component component)

       {

              super(component);

       }

       public void operation()

       {

              super.operation();

              this.addedOperation();

       }

       public void addedOperation()

       {

              System.out.println("ConcreteDecorator.addedOperation()");

       }

}

 

/**

 * 用戶端類

 * @author suki

 */

public class Client {

       public static void main(String[] args) {

              Component component = new ConcreteComponent();

              Decorator decorator = new ConcreteDecorator(component);

              //用戶端不變, 但已增加了責任

              decorator.operation();

       }

}

 

總結:

在[GOF95]的書中:裝飾模式將更多的功能動態地附加到一個對象上。對功能擴充而言,裝飾模式提供了一個靈活的、可以替代繼承的選擇。

本書中451頁的發票系統的例子,好!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.