现在的位置: 首页 > 综合 > 正文

策略模式【设计模式学习-02】

2012年09月30日 ⁄ 综合 ⁄ 共 2268字 ⁄ 字号 评论关闭

      策略模式作为一种软件设计模式,指对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。比如每个人都要“交个人所得税”,但是“在美国交个人所得税”和“在中国交个人所得税”就有不同的算税方法。

      策略模式的UML类图如下: 

策略模式的组成

      —抽象策略角色: 策略类,通常由一个接口或者抽象类实现。 

  —具体策略角色:包装了相关的算法和行为。 


  —环境角色:持有一个策略类的引用,最终给客户端调用。

概念

      策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。(原文:The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.) 

  Context(应用场景): 

  1、需要使用ConcreteStrategy提供的算法。 

  2、 内部维护一个Strategy的实例。 

  3、 负责动态设置运行时Strategy具体的实现算法。 

  4、负责跟Strategy之间的交互和数据传递。 

  Strategy(抽象策略类): 

  1、 定义了一个公共接口,各种不同的算法以不同的方式实现这个接口,Context使用这个接口调用不同的算法,一般使用接口或抽象类实现。 

  ConcreteStrategy(具体策略类): 


  2、 实现了Strategy定义的接口,提供具体的算法实现。

应用场景

      应用场景: 

  1、 多个类只区别在表现行为不同,可以使用Strategy模式,在运行时动态选择具体要执行的行为。

  2、 需要在不同情况下使用不同的策略(算法),或者策略还可能在未来用其它方式来实现。


  3、 对客户隐藏具体策略(算法)的实现细节,彼此完全独立。

优缺点

      优点: 

  1、 提供了一种替代继承的方法,而且既保持了继承的优点(代码重用)还比继承更灵活(算法独立,可以任意扩展)。 

  2、 避免程序中使用多重条件转移语句,使系统更灵活,并易于扩展。 

  3、 遵守大部分GRASP原则和常用设计原则,高内聚、低偶合。 

  缺点: 


  1、 因为每个具体策略类都会产生一个新类,所以会增加系统需要维护的类的数量。

用代码实现(代码是程序员交流最直接的语言!):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _02策略模式
{
class Program
{
static void Main()
{
Context context;

// Three contexts following different strategies
context = new Context(new ConcreteStrategyA());
context.Execute();

context = new Context(new ConcreteStrategyB());
context.Execute();

context = new Context(new ConcreteStrategyC());
context.Execute();

}
}
// The classes that implement a concrete strategy should implement this
// The context class uses this to call the concrete strategy
interface IStrategy
{
void Execute();
}

// Implements the algorithm using the strategy interface
class ConcreteStrategyA : IStrategy
{
public void Execute()
{
Console.WriteLine("Called ConcreteStrategyA.Execute()");
}
}

class ConcreteStrategyB : IStrategy
{
public void Execute()
{
Console.WriteLine("Called ConcreteStrategyB.Execute()");
}
}

class ConcreteStrategyC : IStrategy
{
public void Execute()
{
Console.WriteLine("Called ConcreteStrategyC.Execute()");
}
}

// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context
{
IStrategy strategy;

// Constructor
public Context(IStrategy strategy)
{
this.strategy = strategy;
}

public void Execute()
{
strategy.Execute();
}
}
}

结束语:

      策略模式和前面的简单工厂模式之间的关系可以说是:“既区别又联系,只可意会不可言传!”,上面的博文如果总结的话,通篇都是对策略模式UML图的说明~

      希望能对各位博友有点帮助~

抱歉!评论已关闭.