My simple understanding of the rule mode is to separate the behavior (method) and combine the behavior and entity in the form of a combination (Has-. Another official explanation:
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
There are also a lot of resources on the Internet to introduce this model, and I will not start from scratch. In.. NET provides us with a simple method to implement the policy mode. We can simply regard a delegate as a policy method, it can also be expressed in the form of a group lmabda expression. For example, the Sort method for sorting arrays in. NET is an implementation template of a policy mode.
Copy codeThe Code is as follows:
Static void Main (string [] args)
{
Int [] array = new int [] {3, 2, 8, 1, 5 };
// Equivalent to resetting a sorting Policy
Array. Sort (array, (a, B) => B-);
// Here, an output policy is arranged for each element.
Array. ForEach (array, Console. WriteLine );
}
The two methods of the preceding Array can be regarded as an implementation of the Policy mode in. net.
When I wrote some UI automation earlier, I also used the idea of policy mode for reference. Below is an example of mine: The tested website is a website targeting many markets around the world, sometimes the same test point, we need to configure the network proxy and other different settings to simulate the local market.
Copy codeThe Code is as follows:
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
& Amp; k. MarketName. Contains (market)
Select I). First ();
ProxyStrategy = (Action) Delegate. CreateDelegate (typeof (Action), null, m );
}
Public void RunTest ()
{
ProxyStrategy ();
// Run the main function test later
//......
}
}
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 ");
}
}
}