旧游无处不堪寻
无寻处,惟有少年心
设计模式-策略

策略模式(Strategy Pattern)是一种行为型设计模式,它能让你定义一系列算法,并将每种算法分别放入独立的类中,以使算法的对象能够相互替换。

解释


策略模式建议找出负责用许多不同方式完成特定任务的类,然后将其中的算法抽取到一组被称为策略的独立类中。名为上下文的原始类必须包含一个成员变量来存储对于每种策略的引用。上下文并不执行任务,而是将工作委派给已连接的策略对象。上下文不负责选择符合任务需要的算法,客户端会将所需策略传递给上下文。

上下文可独立于具体策略。这样你就可在不修改上下文代码或其他策略的情况下添加新算法或修改已有算法了。

策略模式 UML


适用场景


  1. 当你想使用对象中各种不同的算法变体,并希望能在运行时切换算法时,可使用策略模式
  2. 当你有许多仅在执行某些行为时略有不同的相似类时,可使用策略模式
  3. 当类中使用了复杂条件运算符以在同一算法的不同变体中切换时,可使用该模式

代码示例


using System;
namespace StrategyPatternDemo
{
// The Context defines the interface of interest to clients.
class Context
{
// The Context maintains a reference to one of the Strategy objects. The
// Context does not know the concrete class of a strategy. It should
// work with all strategies via the Strategy interface.
private IStrategy _strategy;

public Context()
{ }

// Usually, the Context accepts a strategy through the constructor, but
// also provides a setter to change it at runtime.
public Context(IStrategy strategy)
{
this._strategy = strategy;
}

// Usually, the Context allows replacing a Strategy object at runtime.
public void SetStrategy(IStrategy strategy)
{
this._strategy = strategy;
}

// The Context delegates some work to the Strategy object instead of
// implementing multiple versions of the algorithm on its own.
public void DoSomeBusinessLogic()
{
Console.WriteLine("Context: Sorting data using the strategy (not sure how it'll do it)");
var result = this._strategy.DoAlgorithm(new List<string> { "a", "b", "c", "d", "e" });

string resultStr = string.Empty;
foreach (var element in result as List<string>)
{
resultStr += element + ",";
}

Console.WriteLine(resultStr);
}
}

// The Strategy interface declares operations common to all supported
// versions of some algorithm.
//
// The Context uses this interface to call the algorithm defined by Concrete
// Strategies.
public interface IStrategy
{
object DoAlgorithm(object data);
}

// Concrete Strategies implement the algorithm while following the base
// Strategy interface. The interface makes them interchangeable in the
// Context.
class ConcreteStrategyA : IStrategy
{
public object DoAlgorithm(object data)
{
var list = data as List<string>;
list.Sort();

return list;
}
}

class ConcreteStrategyB : IStrategy
{
public object DoAlgorithm(object data)
{
var list = data as List<string>;
list.Sort();
list.Reverse();

return list;
}
}

class Program
{
static void Main(string[] args)
{
// The client code picks a concrete strategy and passes it to the
// context. The client should be aware of the differences between
// strategies in order to make the right choice.
var context = new Context();

Console.WriteLine("Client: Strategy is set to normal sorting.");
context.SetStrategy(new ConcreteStrategyA());
context.DoSomeBusinessLogic();

Console.WriteLine();

Console.WriteLine("Client: Strategy is set to reverse sorting.");
context.SetStrategy(new ConcreteStrategyB());
context.DoSomeBusinessLogic();
// output

// Client: Strategy is set to normal sorting.
// Context: Sorting data using the strategy (not sure how it'll do it)
// a,b,c,d,e

// Client: Strategy is set to reverse sorting.
// Context: Sorting data using the strategy (not sure how it'll do it)
// e,d,c,b,a
}
}
}