程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> .NET 下運用策略模式(組合行為和實體的一種模式)

.NET 下運用策略模式(組合行為和實體的一種模式)

編輯:ASP.NET基礎
我簡單的理解策略模式就是把行為(方法)單獨的抽象出來,並采用組合(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的方法就是一個策略模式的實現模板。
復制代碼 代碼如下:
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");
}
}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved