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