策略模式作爲一種軟件設計模式，指對象有某個行爲，但是在不同的場景中，該行爲有不同的實現算法。比如每個人都要"交個人所得稅"，但是"在美國交個人所得稅"和"在中華民國交個人所得稅"就有不同的算稅方法。

策略模式：

* 定义了一族算法（业务规则）；
* 封装了每个算法；
* 这族的算法可互换代替（interchangeable）。

结构
--

Strategy Pattern in UML 
Strategy pattern in LePUS3 (legend)

示例
--

### C++

```
#include <iostream>

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 ConcreteStrategyC: public StrategyInterface
{
 public:
 virtual void execute()
 {
 cout << "Called ConcreteStrategyC execute method" << endl;
 }
};

class Context
{
 private:
 StrategyInterface \*\_strategy;

 public:
 Context(StrategyInterface \*strategy):\_strategy(strategy)
 {
 }

 void set\_strategy(StrategyInterface \*strategy)
 {
 \_strategy = strategy;
 }

 void execute()
 {
 \_strategy->execute();
 }
};

int main(int argc, char \*argv[])
{
 ConcreteStrategyA concreteStrategyA;
 ConcreteStrategyB concreteStrategyB;
 ConcreteStrategyC concreteStrategyC;

 Context contextA(&concreteStrategyA);
 Context contextB(&concreteStrategyB);
 Context contextC(&concreteStrategyC);

 contextA.execute();
 contextB.execute();
 contextC.execute();
 
 contextA.set\_strategy(&concreteStrategyB);
 contextA.execute();
 contextA.set\_strategy(&concreteStrategyC);
 contextA.execute();

 return 0;
}

```

### Java

```
//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();

 context = new Context(new ThirdStrategy());
 context.execute();

 }

}

// 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()");
 }
 
}

class ThirdStrategy implements Strategy {

 public void execute() {
 System.out.println("Called ThirdStrategy.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();
 }

}

```

### C#

```
using System;

namespace Wikipedia.Patterns.Strategy
{
 // 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();

 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();
 }
 }
}

```

### ActionScript 3

```
//invoked from application.initialize
private function init() : void
{
 var context:Context;

 context = new Context( new ConcreteStrategyA() );
 context.execute();

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

 context = new Context( new ConcreteStrategyC() );
 context.execute();
}

package org.wikipedia.patterns.strategy
{
 public interface IStrategy
 {
 function execute() : void ;
 }
}

package org.wikipedia.patterns.strategy
{
 public final class ConcreteStrategyA implements IStrategy
 {
 public function execute():void
 {
 trace( "ConcreteStrategyA.execute(); invoked" );
 }
 }
}

package org.wikipedia.patterns.strategy
{
 public final class ConcreteStrategyB implements IStrategy
 {
 public function execute():void
 {
 trace( "ConcreteStrategyB.execute(); invoked" );
 }
 }
}

package org.wikipedia.patterns.strategy
{
 public final class ConcreteStrategyC implements IStrategy
 {
 public function execute():void
 {
 trace( "ConcreteStrategyC.execute(); invoked" );
 }
 }
}

package org.wikipedia.patterns.strategy
{
 public class Context
 {
 private var strategy:IStrategy;
 
 public function Context(strategy:IStrategy)
 {
 this.strategy = strategy;
 }
 
 public function execute() : void
 { 
 strategy.execute();
 }
 }
}

```

### PHP

```
<?php
class StrategyExample {
    public function \_\_construct() {
        $context = new Context(new ConcreteStrategyA());
        $context->execute();

        $context = new Context(new ConcreteStrategyB());
        $context->execute();

        $context = new Context(new ConcreteStrategyC());
        $context->execute();
    }
}

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 ConcreteStrategyC implements IStrategy {
    public function execute() {
        echo "Called ConcreteStrategyC execute method\n";
    }
}

class Context {
    var $strategy;

    public function \_\_construct(IStrategy $strategy) {
        $this->strategy = $strategy;
    }

    public function execute() {
        $this->strategy->execute();
    }
}

new StrategyExample;
?>

```

### Objective-C

```
@protocol Strategy <NSObject>

@required
- (void)print;

@end

@interface ConcreteStrategyA : NSObject<Strategy>
{
 
}

@end

@interface ConcreteStrategyB : NSObject<Strategy>
{
 
}

@end

@interface Context : NSObject
{
 id<Strategy> \_strategy;
}

@property (nonatomic, assign) id<Strategy> strategy;

-(void)doIt;

@end

@implementation ConcreteStrategyA

- (void)print
{
 NSLog(@"Test01");
}

@end

@implementation ConcreteStrategyB

- (void)print
{
 NSLog(@"Test02");
}

@end

@implementation Context

@synthesize strategy = \_strategy;

-(void)doIt
{
 [self.strategy print];
}

@end

```

  


|  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 

| * 
* 论
* 编
软件设计模式 |
| --- |
|  |
| 设计模式 | 

|  |  |
| --- | --- |
| 创建型 | 
* 抽象工厂
* 生成器
* 工厂方法
* 惰性初始
* 原型
* 单例

 |
|  |
| 结构型 | 
* 适配器
* 桥接
* Composite（英语：）
* 修饰
* 外观
* 享元
* 代理

 |
|  |
| 行为型 | 
* 责任链
* 命令
* Interpreter（英语：）
* 迭代器
* 中介者
* Memento（英语：）
* 观察者
* Specification（英语：）
* State（英语：）
* 策略
* 模板方法
* 访问者

 |

 |
|  |
| 并行模式 | 
* 主动对象（英语：）
* 阻止（英语：）
* Binding properties（英语：）
* 双重检查锁定模式
* 异步方法调用
* Future与promise
* Guarded suspension（英语：）
* Join（英语：）
* 锁
* Messaging（英语：）
* 监视器
* Proactor（英语：）
* 反应器
* 读写锁
* 调度
* 线程池
* 线程局部存储

 |
|  |
| 架构模式 | 
* ADR（英语：）
* 主动记录
* Broker（英语：）
* 主從式架構
* cbd
* DAO
* DDD
* Data transfer object（英语：）
* Front controller（英语：）
* Identity map（英语：）
* Interceptor（英语：）
* 控制反转
* MVC
* 微服務
* MVP
* 單體式應用程式
* 多层架构
* *n*-tier（英语：）
* Naked objects（英语：）
* P2P
* 发布/订阅
* REST
* SOA
* Specification（英语：）

 |
|  |
| 云分布式 | 
* 断路器
* CQRS（英语：）
* 补偿交易（英语：）
* 索引表
* 领导者选举（英语：）
* MapReduce
* 物化视图（英语：）
* 管道
* 过滤器（英语：）
* 发布/订阅
* 分片（英语：）
* 节流（英语：）

 |
|  |
| 其他模式 | 
* Blackboard（英语：）
* Business delegate（英语：）
* Composite entity（英语：）
* 委托
* 依赖注入
* Intercepting filter（英语：）
* 惰性載入
* Method chaining（英语：）
* 模拟对象
* 空对象
* 对象池
* Servant（英语：）
* Twin（英语：）
* Type tunnel（英语：）

 |
|  |
| 书籍 | 
* 设计模式：可复用面向对象软件的基础
* 企业集成模式（英语：）

 |
|  |
| 人物 | 
* 克里斯托佛·亚历山大
* 埃里希·伽瑪
* Ralph Johnson（英语：）
* John Vlissides（英语：）
* 葛來迪·布區
* 肯特·貝克
* 沃德·坎宁安
* 马丁·福勒
* Robert Martin（英语：）
* Jim Coplien（英语：）
* Douglas Schmidt（英语：）
* Linda Rising

 |
|  |
| 社区 | 
* The Hillside Group（英语：）
* The Portland Pattern Repository（英语：）

 |

 |