C# Design Patterns (2) - Strategy
2009-06-22 08:33:04 来源:WEB开发网图 1 这张为很多书籍和文档都曾出现过的 Strategy 经典 Class Diagram
01_Shell.aspx.cs
using System;
using com.cnblogs.WizardWu.sample01;
//客户程序
public partial class _01_Shell : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//执行对象
Context context;
context = new Context(new ConcreteStrategyA());
Response.Write(context.ContextInterface() + "<br>");
context = new Context(new ConcreteStrategyB());
Response.Write(context.ContextInterface() + "<br>");
context = new Context(new ConcreteStrategyC());
Response.Write(context.ContextInterface() + "<br>");
}
}
namespace com.cnblogs.WizardWu.sample01
{
//抽象算法类 (亦可用接口)。定义了所有策略的公共接口
abstract class Strategy
{
//算法需要完成的功能
public abstract string AlgorithmInterface();
}
//具体算法类A
class ConcreteStrategyA : Strategy
{
//算法A实现方法
public override string AlgorithmInterface()
{
return "算法A实现";
}
}
//具体算法类B
class ConcreteStrategyB : Strategy
{
//算法B实现方法
public override string AlgorithmInterface()
{
return "算法B实现";
}
}
//具体算法类C
class ConcreteStrategyC : Strategy
{
//算法C实现方法
public override string AlgorithmInterface()
{
return "算法C实现";
}
}
//执行对象。需要采用可替换策略执行的对象
class Context
{
Strategy strategy;
public Context(Strategy strategy) //构造函数
{
this.strategy = strategy;
}
//执行对象依赖于策略对象的操作方法
public string ContextInterface()
{
return strategy.AlgorithmInterface();
}
}
} // end of namespace
/*
更多精彩
赞助商链接