.NET 下运用策略模式
2013-04-24 21:23
295 查看
我简单的理解策略模式就是把行为(方法)单独的抽象出来,并采用组合(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的方法就是一个策略模式的实现模板。
之前写一些UI自动化的时候,也借鉴了一下策略模式的思想。下面是我的一个实例:被测试网站是一个针对全球很多市场的一个网站,有时同一个测试点,需要我们配置一下网络代理和其它不同的设置来模拟当地市场。
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的方法就是一个策略模式的实现模板。
static void Main(string[] args) { int[] array = new int[] { 3, 2, 8, 1, 5 }; //相当于是重新设置了一个排序策略 Array.Sort(array, (a, b) => b - a); //这里也相当于为每个元素安排了一个输出策略 Array.ForEach(array, Console.WriteLine); }以上Array的两个方法都可以看成是策略模式在.net中的一种实现。
之前写一些UI自动化的时候,也借鉴了一下策略模式的思想。下面是我的一个实例:被测试网站是一个针对全球很多市场的一个网站,有时同一个测试点,需要我们配置一下网络代理和其它不同的设置来模拟当地市场。
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"); } } }
相关文章推荐
- .NET 下运用策略模式
- .NET 下运用策略模式(组合行为和实体的一种模式)
- 简易运算(运用策略模式实现)
- .NET设计模式(22):策略模式(Strategy Pattern)
- “第一次亲密接触”——iOS中策略模式初运用
- 浅析.net策略模式
- iOS中策略模式初运用
- .NET中的设计模式---策略模式&状态模式
- .NET策略(Strategy)模式
- 游戏项目中运用到的设计模式(二)...策略模式(strategy)(《重构-改善既有代码的设计》读后做)
- 在c#中运用策略模式(在看过鸭子应用之后)
- IOS中策略模式初运用
- 详解Python设计模式编程中观察者模式与策略模式的运用
- 运用单例模式、建造者模式和策略模式实现异步加载Android联系人资料
- [★] .NET 偶尔连接的设计策略 -联机状态- 脱机模式- 数据同步
- 内部类综合运用 温室的运作(策略模式)
- 步步为营 .NET 设计模式学习笔记 三、Strategy(策略模式)
- .NET简谈设计模式之(策略模式)
- [.net 面向对象程序设计深入](26)实战设计模式——策略模式 Strategy (行为型)