我简单的理解策略模式就是把行为(方法)单独的抽象出来,并采用组合(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"); } } }