天天看點

政策模式

政策模式定義了一系列的算法,并将每一個算法封裝起來,而且使它們還可以互相替換。政策模式讓算法獨立于使用它的客戶而獨立變化。

(原文:The Strategy Pattern defines a family of

algorithms,encapsulates each one,and makes them interchangeable. Strategy lets

the algorithm vary independently from clients that use it.)

Context(應用場景):

1、需要使用ConcreteStrategy提供的算法。

2、 内部維護一個Strategy的執行個體。

3、 負責動态設定運作時Strategy具體的實作算法。

4、負責跟Strategy之間的互動和資料傳遞。

Strategy(抽象政策類):

1、

定義了一個公共接口,各種不同的算法以不同的方式實作這個接口,Context使用這個接口調用不同的算法,一般使用接口或抽象類實作。

ConcreteStrategy(具體政策類):

2、 實作了Strategy定義的接口,提供具體的算法實作。

政策模式

政策模式與簡單工廠模式組合:

政策模式

同樣地,政策模式可以與工廠方法模式或抽象工廠模式組合。