Strategy策略模式是一種對象行為模式。主要是應(yīng)對:在軟件構(gòu)建過程中,某些對象使用的算法可能多種多樣,經(jīng)常發(fā)生變化。如果在對象內(nèi)部實(shí)現(xiàn)這些算法,將會使對象變得異常復(fù)雜,甚至?xí)斐尚阅苌系呢?fù)擔(dān)。
GoF《設(shè)計(jì)模式》中說道:定義一系列算法,把它們一個個封裝起來,并且使它們可以相互替換。該模式使得算法可獨(dú)立于它們的客戶變化。
Strategy模式的結(jié)構(gòu)圖如下:
從圖中我們不難看出:Strategy模式實(shí)際上就是將算法一一封裝起來,如圖上的ConcreteStrategyA、ConcreteStrategyB、ConcreteStrategyC,但是它們都繼承于一個接口,這樣在Context調(diào)用時就可以以多態(tài)的方式來實(shí)現(xiàn)對于不用算法的調(diào)用。
Strategy模式的實(shí)現(xiàn)如下:
我們現(xiàn)在來看一個場景:我在下班在回家的路上,可以有這幾種選擇,走路、騎車、坐車。首先,我們需要把算法抽象出來:
public interface IStrategy
{
void OnTheWay();
}
接下來,我們需要實(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)一個走路回家的場景:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Arrive to home");
IStrategy strategy = new WalkStrategy();
strategy.OnTheWay();
Console.Read();
}
}
運(yùn)行結(jié)果如下;
Arrive to home
Walk on the road
如果我們需要實(shí)現(xiàn)其他的方法,只需要在Context改變一下IStrategy所示例化的對象就可以。
posted on 2008-06-18 09:38
天書 閱讀(169)
評論(0) 編輯 收藏 引用