Design Pattern Explained 讀書筆記四——Strategy,patternexplained

來源:互聯網
上載者:User

Design Pattern Explained 讀書筆記四——Strategy,patternexplained
What?

Define a family of algorithms, encapsulate each one, and
make them interchangeable. Strategy lets the algorithm
vary independently from the clients that use it. ——GOF

定義一系列演算法,封裝每一個,並且使每個封裝是可相互替換的。Strategy模式,做到了 以獨立於使用這些演算法的用戶端的方式 , 替換這一系列演算法演算法。自由替換每種演算法,不受用戶端束縛。

官網執行個體:

public class TaskController {    public void process () {        // this code is an emulation of a         // processing task controller        // . . .        // figure out which country you are in        CalcTax myTax;        myTax= getTaxRulesForCountry();        SalesOrder mySO= new SalesOrder();        mySO.process(myTax);    }    private CalcTax getTaxRulesForCountry() {        // In real life, get the tax rules based on        // country you are in. You may have the        // logic here or you may have it in a        // configuration file        // Here, just return a USTax so this         // will compile.        return new USTax();    }}public class SalesOrder {    public void process (CalcTax taxToUse) {        long itemNumber= 0;        double price= 0;        // given the tax object to use        // . . .        // calculate tax        double tax = taxToUse.taxAmount(itemNumber,price);    }}public abstract class CalcTax {    abstract public double taxAmount(long itemSold,double price);}public class CanTax extends CalcTax {    public double taxAmount(long itemSold,double price) {        // in real life, figure out tax according to        // the rules in Canada and return it        // here, return 0 so this will compile        return 0.0;    }}public class USTax extends CalcTax {    public double taxAmount(long itemSold,double price) {        // in real life, figure out tax according to        // the rules in the US and return it        // here, return 0 so this will compile        return 0.0;    }}
The Strategy Pattern: Key Features (關鍵特點)
  • Intent(目的):
    允許你根據不同的環境(上下文情況),使用不同的商務邏輯或者演算法。

    Allows you to use different business rules or algorithms depending
    upon the context in which they occur.

  • Problem(應用情境):
    如何選擇合適、匹配的演算法 取決於用戶端的請求或邏輯的執行。假如,你的選擇演算法唯一,你並不需要Strategy模式。
    當分析到 要根據不同情況去選擇不同業務方案,考慮下Strategy!

    The selection of an algorithm that needs to be applied depends upon
    the client making the request or the data being acted upon. If you
    simply have a rule in place that does not change, you do not need a
    Strategy pattern.

  • Solution(具體方案):
    將演算法的選擇與演算法的實現分離開來。允許根據上下文去對演算法做選擇。

    Separates the selection of algorithm from the implementation of the
    algorithm. Allows for the selection to be made based upon context.

  • Participants and Collaborators:

    Strategy策略明確了 不同演算法被使用的 方式。
    1.每個具體的 Stragety 類 實現了 每個具體的演算法(或商務邏輯)。
    2.上下文Context根據 一個 Strategy類型的引用 來選擇 具體的演算法( Stragety).也就是說對演算法的選擇,是Context和Stragety類型的互動結果。
    3.Context將來自Clinet的請求轉給 Stragety.

    The strategy specifies how the different algorithms are used.
    • The concreteStrategies implement these different algorithms.
    • The Context uses the specific ConcreteStrategy with a reference of
    type Strategy. The strategy and Context interact to implement the
    chosen algorithm (sometimes the strategy must query the Context).
    • The Context forwards requests from its Client to the Strategy.

  • Consequences(效果):
    1 .Strategy模式 定義了一系列 演算法(商務邏輯)
    2 .消除 switch、if else 等語句。
    3 . 用同一種方式調用所有演算法(因為有多態)。演算法實作類別與Context內容相關的互動 也許需要Context調用額外的 Context.getState() 。
    4.每個Stragety實現都是一個獨立的類,簡化了測試的難度。

    • The Strategy pattern defines a family of algorithms.
    • Switches and/or conditionals can be eliminated.
    • You must invoke all algorithms in the same way (they must all have the same interface). The interaction between the ConcreteStrategies and the Context may require the addition of getstate type methods to the Context.

  • Implementation
    讓使用演算法的類(Context)包含一個抽象類別(Strategy),該抽象類別中
    有一個抽象方法指定如何調用演算法。每個衍生類別按需要實現演算法。
    注意:在原型Stragety模式中,選擇所用具體實作類別的職責由Client對象承擔,並轉給Strategy模式的Context對象。

Have the class that uses the algorithm (the Context) contain an
abstract class (the stragegy) that has an abstract method pecifying
how to call the algorithm. Each derived class implements the algorithm
as needed. Note: this method wouldn’t be abstract if you wanted to
have some default behavior. Note: In the prototypical Strategy
pattern, the responsibility for selecting the particular
implementation to use is done by the Client object and is given to the
context of the Strategy pattern.

  • Strategy與Context的耦合
    Strategy模式要求所封裝的演算法 必須處在 使用他們的類(Context)之外。也就是以為這 要麼把Strategy需要的資訊傳給它(Strategy),要麼以其他形式獲得。
缺點:

不得不建立多個額外的類。但如果不考慮擴充演算法的情況下,可以在抽象類別 **Strategy中 用內部類包含所有演算法。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

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