策略模式

在计算机编程中，策略模式是一种行为型软件设计模式，它确使可以在运行时选择算法。不再直接的实现一个单一的算法，代码接收运行时指令，选择一个算法家族中的某个算法。
概述.
策略模式：
结构.
在上面的UML类图中，codice_1类不直接实现算法。codice_1转而提及codice_3接口来实行一个算法（codice_4），这使得codice_1独立于算法是如何是实现的。codice_6和codice_7类实现了codice_3接口，就是说实现（封装）了一个算法。
UML序列图展示运行时交互：codice_1对象委托一个算法至不同的codice_3对象。首先codice_1调用codice_12于codice_6对象之上，它实行算法并将结果返回给codice_1。此后，codice_1变更它的策略并调用codice_12在codice_7对象之上，它实行一个算法并将结果返回给codice_1。
示例.
C++.
下面是C++的例子：
using namespace std;
class StrategyInterface {
public:
 virtual void execute() = 0;
class ConcreteStrategyA: public StrategyInterface {
public:
 virtual void execute() {
 cout « "Called ConcreteStrategyA execute method" « endl;
};
class ConcreteStrategyB: public StrategyInterface {
public:
 virtual void execute() {
 cout « "Called ConcreteStrategyB execute method" « endl;
};
class Context {
private:
 StrategyInterface *_strategy;
public:
 Context(StrategyInterface *strategy):_strategy(strategy) {
 void set_strategy(StrategyInterface *strategy) {
 _strategy = strategy;
 void execute() {
 _strategy-&gt;execute();
};
int main(int argc, char *argv[])
 ConcreteStrategyA concreteStrategyA;
 ConcreteStrategyB concreteStrategyB;
 Context contextA(&amp;concreteStrategyA);
 Context contextB(&amp;concreteStrategyB);
 contextA.execute();
 contextB.execute();
 contextA.set_strategy(&amp;concreteStrategyB);
 contextA.execute();
 return 0;
Java.
下面是Java的例子：
// The classes that implement a concrete strategy should implement this
// The context class uses this to call the concrete strategy
interface Strategy {
 void execute();
// Implements the algorithm using the strategy interface
class FirstStrategy implements Strategy {
 public void execute() {
 System.out.println("Called FirstStrategy.execute()");
class SecondStrategy implements Strategy {
 public void execute() {
 System.out.println("Called SecondStrategy.execute()");
// Configured with a ConcreteStrategy object and maintains a reference to a Strategy object
class Context {
 Strategy strategy;
 // Constructor
 public Context(Strategy strategy) {
 this.strategy = strategy;
 public void execute() {
 this.strategy.execute();
//StrategyExample test application
class StrategyExample {
 public static void main(String[] args) {
 Context context;
 // Three contexts following different strategies
 context = new Context(new FirstStrategy());
 context.execute();
 context = new Context(new SecondStrategy());
 context.execute();
C#.
下面是C#的例子：
using System;
namespace Wikipedia.Patterns.Strategy {
 // 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()" );
 // 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();
 // MainApp test application
 class MainApp {
 static void Main() {
 Context context;
 // Three contexts following different strategies
 context = new Context(new ConcreteStrategyA());
 context.Execute();
 context = new Context(new ConcreteStrategyB());
 context.Execute();
Python.
下面是Python的例子：
from abc import ABC, abstractmethod
class Strategy(ABC):
 @abstractmethod
 def execute(self): pass
class ConcreteStrategyA(Strategy):
 def execute(self): 
 print("Called ConcreteStrategyA execute method")
class ConcreteStrategyB(Strategy):
 def execute(self): 
 print("Called ConcreteStrategyB execute method")
class Context():
 def __init__(self, strategy):
 self.strategy = strategy
 def execute(self):
 self.strategy.execute()
其执行：
»&gt; context = Context(ConcreteStrategyA())
»&gt; context.execute()
Called ConcreteStrategyA execute method
»&gt; context = Context(ConcreteStrategyB())
»&gt; context.execute()
Called ConcreteStrategyB execute method
PHP.
下面是PHP的例子：
&lt;?php
interface IStrategy {
 public function execute();
class ConcreteStrategyA implements IStrategy {
 public function execute() {
 echo "Called ConcreteStrategyA execute method\n";
class ConcreteStrategyB implements IStrategy {
 public function execute() {
 echo "Called ConcreteStrategyB execute method\n";
class Context {
 var $strategy;
 public function __construct(IStrategy $strategy) {
 $this-&gt;strategy = $strategy;
 public function execute() {
 $this-&gt;strategy-&gt;execute();
class StrategyExample {
 public function __construct() {
 $context = new Context(new ConcreteStrategyA());
 $context-&gt;execute();
 $context = new Context(new ConcreteStrategyB());
 $context-&gt;execute();
new StrategyExample;