My simple understanding of the strategy pattern is to abstract the behavior (method) separately and use a combination (HAS-A) approach to combine the behavior and the entity's pattern. One more official explanation:
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients this use it.
There are a lot of resources on the Internet to introduce this model, I do not start from the beginning. Delegating to us in. NET gives us a simple way to implement a policy pattern, simply by seeing a delegate as a policy approach, and by expressing it in the form of a group of LMABDA expressions. Like what. NET is an implementation template for a policy pattern.
Copy Code code as follows:
static void Main (string[] args)
{
int[] array = new int[] {3, 2, 8, 1, 5};
The equivalent of a sort policy reset
Array.Sort (Array, (A, B) => b-a);
This is also the equivalent of arranging an output policy for each element
Array.foreach (Array, Console.WriteLine);
}
The two methods of the array above can be viewed as an implementation of the policy pattern in. Net.
Before writing some UI Automation, it also draws on the idea of a strategic model. Here is an example of me: The test site is a site for many markets around the world, sometimes the same test point, we need to configure the network agent and other different settings to simulate the local market.
Copy Code code 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-I.getcustomattributes (False)
Let k = j as Market
where k!= null
&& K.marketname.contains (Market)
Select i). A ();
Proxystrategy = (action) delegate.createdelegate (typeof (action), NULL, M);
}
public void Runtest ()
{
Proxystrategy ();
Then run the main functional test
//......
}
}
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 ("A proxy");
}
[Market ("EN-GB")]
public void Setukproxy ()
{
Console.WriteLine ("UK proxy");
}
}
}