设计模式学习笔记-策略模式

策略模式:Strategy,它定义了算法家族,分别封装起来,让他们之间可以相互替换,让算法的变化不会影响到算法使用者

1.定义抽象算法

    /// <summary>
/// 抽象算法类
/// </summary>
abstract class Strategy
{
/// <summary>
/// 算法方法 接口定义
/// </summary>
public abstract void AlgorithmInterface();
}

2.具体算法的实现

  /// <summary>
/// 具体算法A
/// </summary>
class ConcreteStrategyA : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine(
"算法A的实现");
}
}
/// <summary>
/// 具体算法B
/// </summary>
class ConcreteStrategyB : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine(
"算法B的实现");
}
}
/// <summary>
/// 具体算法C
/// </summary>
class ConcreteStrategyC : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine(
"算法C的实现");
}
}

3.调度类

    /// <summary>
/// 承上启下的算法调用
/// </summary>
class Context
{
Strategy strategy;
/// <summary>
/// 传入具体策略对象
/// </summary>
/// <param name="strategy"></param>
public Context(Strategy strategy)
{
this.strategy = strategy;
}
/// <summary>
/// 根据策略对象的值判断调用的算法类
/// </summary>
public void ContextInterface()
{
strategy.AlgorithmInterface();
}
}

  客户端调用:

        /// <summary>
/// 测试策略
/// </summary>
static void TestStrategy()
{
Context context;
//策略A
context = new Context(new ConcreteStrategyA());
context.ContextInterface();
//策略B
context = new Context(new ConcreteStrategyB());
context.ContextInterface();
//策略C
context = new Context(new ConcreteStrategyC());
context.ContextInterface();
Console.Read();
}

  策略模式比较简单但是应用非常的多


posted @ 2011-08-16 09:16  叶鹏  阅读(677)  评论(0编辑  收藏  举报