# [设计模式]行为型模式-策略模式

## 示例代码

### Go

strategy.go

package strategy

// CalStrategy 是一个策略类
type CalStrategy interface {
do(int, int) int
}

func (*Add) do(a, b int) int {
return a + b
}

// Reduce 为减法策略
type Reduce struct{}

func (*Reduce) do(a, b int) int {
return a - b
}

// Operator 是具体的策略执行者
type Operator struct {
strategy CalStrategy
}

// 设置策略
func (o *Operator) setStrategy(strategy CalStrategy) {
o.strategy = strategy
}

// 调用策略中的方法
func (o *Operator) calc(a, b int) int {
return o.strategy.do(a, b)
}


package strategy

import "testing"

func TestStrategy(t *testing.T) {
operator := Operator{}
if operator.calc(1, 2) != 3 {
}

operator.setStrategy(&Reduce{})
if operator.calc(2, 1) != 1 {
t.Fatal("Reduce strategy error")
}
}


### Python

from abc import ABC, abstractmethod

class CalStrategy(ABC):
"""策略类
"""
@abstractmethod
def do(self, a: int, b: int) -> int:
pass

"""加法策略
"""
def do(self, a: int, b: int) -> int:
return a + b

class Reduce(CalStrategy):
"""减法策略
"""
def do(self, a: int, b: int) -> int:
return a - b

class Operator:
"""策略执行者
"""
def __init__(self):
self.strategy = None

def set_strategy(self, strategy: CalStrategy):
"""设置策略
"""
self.strategy = strategy

def calc(self, a: int, b: int) -> int:
"""调用策略中的方法
"""
return self.strategy.do(a, b)

if __name__ == "__main__":
operator = Operator()