原文:乐在其中设计模式(C#) - 策略模式(Strategy Pattern)
[索引页][源码下载]
乐在其中设计模式(C#) - 策略模式(Strategy Pattern)
作者:webabcd
介绍
定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法的变化可独立于使用它的客户。
示例
有一个Message实体类,对它的操作有Insert()和Get()方法,持久化数据在SqlServer数据库中或Xml文件里(两种可互换的算法)。由客户端决定使用哪种算法。

MessageModel
IMessageStrategy
SqlMessage
XmlMessage
Message
client

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;


using Pattern.Strategy;


public partial class Strategy : System.Web.UI.Page



{

protected void Page_Load(object sender, EventArgs e)


{

Message m = new Message(new XmlMessage());

Response.Write(m.Insert(new MessageModel("插入", DateTime.Now)));

Response.Write("<br />");

Response.Write(m.Get()[].PublishTime.ToString());

Response.Write("<br />");


m = new Message(new SqlMessage());

Response.Write(m.Insert(new MessageModel("插入", DateTime.Now)));

Response.Write("<br />");

Response.Write(m.Get()[].PublishTime.ToString());

Response.Write("<br />");

}

}
运行结果
True
XML方式获取Message 2007-2-10 22:42:44
True
SQL方式获取Message 2007-2-10 22:42:44
参考
http://www.dofactory.com/Patterns/PatternStrategy.aspx
OK
[源码下载]