.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");
}
}
}

时间: 2024-09-16 00:14:31

.NET 下运用策略模式(组合行为和实体的一种模式)_实用技巧的相关文章

asp.net遍历文件夹下所有子文件夹并绑定到gridview上的方法_实用技巧

遍历文件夹下所有子文件夹,并且遍历配置文件某一节点中所有key,value并且绑定到GridView上 Helper app_Helper = new Helper(); DataSet ds = new DataSet(); DataTable dt = new DataTable(); protected void Page_Load(object sender, EventArgs e) { gvwBind(); } #region 绑定GridView /// <summary> //

.Net下二进制形式的文件(图片)的存储与读取详细解析_实用技巧

.Net下图片的常见存储与读取凡是有以下几种:存储图片:以二进制的形式存储图片时,要把数据库中的字段设置为Image数据类型(SQL Server),存储的数据是Byte[]. 1.参数是图片路径:返回Byte[]类型: 复制代码 代码如下: public byte[] GetPictureData(string imagepath)        {            ////根据图片文件的路径使用文件流打开,并保存为byte[]               FileStream fs =

asp.net下获取远程网页的内容之二(downmoon原创)_实用技巧

本文仅针AD下代理上网的情况: 代码如下: 1.定义变量:  定义变量#region  定义变量 复制代码 代码如下: private    string strFireWallIP          ...{              get              ...{                  return System.Configuration.ConfigurationSettings.AppSettings["strFireWallIP"];        

asp.net gridview分页:第一页 下一页 1 2 3 4 上一页 最末页_实用技巧

效果图: 功能简介:可使用上下键选中行,选中后点击修改,textbox获得gridview中的代码的数据.对你有帮助的话,请记得要点击"好文要顶"哦!!!不懂的,请留言.废话不多说了,贴码如下: <head runat="server"> <title>GridView分頁</title> <script type="text/javascript"> var currentRowId = 0; v

Asp.Net平台下的图片在线裁剪功能的实现代码(源码打包)_实用技巧

1.前台展现实现 网上找到这个jquery.Jcrop,稍看了下,发现它提供的效果完全能满足项目需求. 官方网址:http://deepliquid.com/content/Jcrop.html,感兴趣的朋友可去看看. 页面先引用相关样式和脚本: 复制代码 代码如下: <link href="Styles/jquery.Jcrop.css" rel="stylesheet" type="text/css" /> <script

asp.net下通过泛解析和伪静态实现二级域名的实现方法_实用技巧

虽然最后是实现了,但身为程序员的我,却总是感觉利用其他不开源的组件自己总把握不了技术的核心.其实在net中微软已经为我们留下了接口,让我们为所欲为了. 首先我们可以通过一张图大概了解下.net的生命周期. 从 上图可以看出来,针对每个不同用户的请求,服务器都会创建一个新的HttpContext实例直到请求结束,服务器销毁这个实例.而 Ihttpcontext是httpcontext对外公开的接口,它包含了2个方法:dispose()和Init(HttpApplication context),我

asp.net下检测远程URL是否存在的三种方法_实用技巧

复制代码 代码如下: private void Page_Load(object sender, System.EventArgs e) { string url1 = "http://s.jb51.net/"; string url2 = "yun_qi_img/logo.gif"; Response.Write("<li>方法1:"); Response.Write(url1 + " 存在:" + UrlExi

ASP.NET下上传图片到数据库,并且读出图片的代码(详细版)_实用技巧

首先在SQL Server中建立一个图片存储的数库表,ImageData Column为图象二进制数据储存字段,ImageContentType Column为图象文件类型记录字段,ImageDescription Column为储蓄图 象文件说明字段,ImageSize Column为储存图象文件长度字段,结构如下: 复制代码 代码如下: CREATE TABLE [dbo].[ImageStore] ( [ImageID] [int] IDENTITY (1, 1) NOT NULL , [

asp.net下无法循环绑定投票的标题和选项的解决方法_实用技巧

问题:1,无法循环绑定投票的标题和选项 解决方法: 在Repeater绑定中添加ItemDataBound事件,选项用RadioButtonList绑定,附源代码: Default页,源页面 复制代码 代码如下: <div> 广大网友对保障房建设相关问题调查<br /> <asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemData