时间:2021-07-01 10:21:17 帮助过:27人阅读
输出策略
static void Main(string[] args)
{
int[] array = new int[] { 3, 2, 8, 1, 5 };
//相当于是重新设置了一个排序策略
Array.Sort(array, (a, b) => b - a);
//这里也相当于为每个元素安排了一个
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");
}
}
}