我簡單的理解策略模式就是把行為(方法)單獨的抽象出來,并采用組合(Has-a)的方式,來組合行為和實體的一種模式。再來個官方的解釋: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. 網上也有很多資源介紹這個模式,我也不從頭說起了。在.NET中委托給我們給我們提供了簡單實現策略模式的方法,可以簡單的把一個委托看成是一種策略方法,而且還能借組lmabda表達式這樣的形式來表達出來。比如,.NET中對數組排序的Sort的方法就是一個策略模式的實現模板。
using System; using System.Linq; namespace StrategyPattern { class Program { static void Main(string[] args) { UITest test = new UITest(); test.RunTest(); test.SetProxy("zh-cn"); test.RunTest(); } } class UITest { Action proxyStrategy; //Default is US market public UITest(String market = "en-us") { setProxy(market); } public void SetProxy(String market) { setProxy(market); } private void setProxy(String market) { Type proxy = typeof(Proxy); var m = (from i in proxy.GetMethods() from j in i.GetCustomAttributes(false) let k = j as Market where k != null && k.MarketName.Contains(market) select i).First(); proxyStrategy = (Action)Delegate.CreateDelegate(typeof(Action), null, m); } public void RunTest() { proxyStrategy(); //之后運行主要的功能測試 //...... } } class Market : Attribute { public String MarketName { get; set; } public Market(String marketName) { this.MarketName = marketName; } } class Proxy { [Market("en-us,es-us")] public void SetUSProxy() { Console.WriteLine("us proxy"); } [Market("zh-cn")] public void SetChinaProxy() { Console.WriteLine("china proxy"); } [Market("en-gb")] public void SetUKProxy() { Console.WriteLine("uk proxy"); } } }