?????? Strategy 策略模式是一種對(duì)象行為模式。主要是應(yīng)對(duì):在軟件構(gòu)建過(guò)程中,某些對(duì)象使用的算法可能多種多樣,經(jīng)常發(fā)生變化。如果在對(duì)象內(nèi)部實(shí)現(xiàn)這些算法,將會(huì)使對(duì)象變得異常復(fù)雜,甚至?xí)斐尚阅苌系呢?fù)擔(dān)。
?????? GoF 《設(shè)計(jì)模式》中說(shuō)道:定義一系列算法,把它們一個(gè)個(gè)封裝起來(lái),并且使它們可以相互替換。該模式使得算法可獨(dú)立于它們的客戶變化。
?????? Strategy
模式的結(jié)構(gòu)圖如下:
?
??????
從圖中我們不難看出:
Strategy
模式實(shí)際上就是將算法一一封裝起來(lái),如圖上的
ConcreteStrategyA
、
ConcreteStrategyB
、
ConcreteStrategyC
,但是它們都繼承于一個(gè)接口,這樣在
Context
調(diào)用時(shí)就可以以多態(tài)的方式來(lái)實(shí)現(xiàn)對(duì)于不用算法的調(diào)用。
?????? Strategy 模式的實(shí)現(xiàn)如下:
?????? 我們現(xiàn)在來(lái)看一個(gè)場(chǎng)景:我在下班在回家的路上,可以有這幾種選擇,走路、騎車、坐車。首先,我們需要把算法抽象出來(lái):
??????
public
interface
IStrategy
??? {
???????
void OnTheWay();
}
接下來(lái),我們需要實(shí)現(xiàn)走路、騎車和坐車幾種方式。
public
class
WalkStrategy : IStrategy
??? {
???????
public
void OnTheWay()
??????? {
???????????
Console.WriteLine("Walk on the road");
??????? }
??? }
???
public
class
RideBickStragtegy : IStrategy
??? {
???????
public
void OnTheWay()
??????? {
???????????
Console.WriteLine("Ride the bicycle on the road");
??????? }
??? }
???
public
class
CarStragtegy : IStrategy
??? {
???????
public
void OnTheWay()
??????? {
???????????
Console.WriteLine("Drive the car on the road");
??????? }
}
最后再用客戶端代碼調(diào)用封裝的算法接口,實(shí)現(xiàn)一個(gè)走路回家的場(chǎng)景:
class
Program
??? {
???????
static
void
??????? {
???????????
Console.WriteLine("Arrive to home");
???????????
IStrategy strategy = newWalkStrategy();
??????????? strategy.OnTheWay();
???????????
Console.Read();
??????? }
}
運(yùn)行結(jié)果如下;
Arrive to home
Walk on the road
如果我們需要實(shí)現(xiàn)其他的方法,只需要在 Context 改變一下 IStrategy 所示例化的對(duì)象就可以。
?????? Strategy 模式的要點(diǎn):
1 、 Strategy 及其子類為組件提供了一系列可重用的算法,從而可以使得類型在運(yùn)行時(shí)方便地根據(jù)需要在各個(gè)算法之間進(jìn)行切換。所謂封裝算法,支持算法的變化。
2 、 Strategy 模式提供了用條件判斷語(yǔ)句以外的另一中選擇,消除條件判斷語(yǔ)句,就是在解耦合。含有許多條件判斷語(yǔ)句的代碼通常都需要 Strategy 模式。
3 、 Strategy 模式已算法為中心,可以和 Factory Method 聯(lián)合使用,在工廠中使用配制文件對(duì)變化的點(diǎn)進(jìn)行動(dòng)態(tài)的配置。這樣就使變化放到了運(yùn)行時(shí)。
4 、與 Template Method 相比, Strategy 模式的中心跟集中在方法的封裝上