namespace StrategyPattern //策略模式
{
/// <summary>
/// 定义所以支持的算法的公共接口
/// </summary>
abstract class Strategy
{
/// <summary>
/// 算法方法。
/// </summary>
public abstract void AlgorithmInrerface();
} class ConcreateStratetyA : Strategy
{
public override void AlgorithmInrerface()
{
Console.WriteLine("实现算法A");
}
} class ConcreateStratetyB : Strategy
{
public override void AlgorithmInrerface()
{
Console.WriteLine("实现算法B");
}
} class ConcreateStratetyC : Strategy
{
public override void AlgorithmInrerface()
{
Console.WriteLine("实现算法C");
}
} /// <summary>
/// 用一个ConcreateStratety来配置,来维护一个对Stratety对象的引用。
/// </summary>
class Context
{
Strategy stratety;
public Context(Strategy stratety)//构造器注入具体的策略对象。
{
this.stratety = stratety;
}
/// <summary>
/// 根据具体策略的对象,调用其算法的方法。
/// </summary>
public void ContextInterface()
{
stratety.AlgorithmInrerface();
}
}
class Program
{
static void Main(string[] args)
{
Context context = null; context = new Context(new ConcreateStratetyA());
context.ContextInterface(); context = new Context(new ConcreateStratetyB());
context.ContextInterface(); context = new Context(new ConcreateStratetyC());
context.ContextInterface(); Console.Read();
}
}
}