策略模式

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

type IStrategy interface {
    Exec(int64, int64) int64
}

type AddStrategy struct {
}

func (*AddStrategy) Exec(a, b int64) int64 {
    return a + b
}

type ReduceStrategy struct {
}

func (*ReduceStrategy) Exec(a, b int64) int64 {
    return a - b
}

type Operator struct {
    IStrategy
}

func (o *Operator) SetStrategy(s IStrategy) {
    o.IStrategy = s
}

func (o *Operator) Calculate(a, b int64) int64 {
    return o.Exec(a, b)
}

使用

o := new(Operator)
add := new(AddStrategy)
reduce := new(ReduceStrategy)
convey.Convey("策略模式", t, func() {
    var a, b int64 = 4, 2
    o.SetStrategy(add)
    convey.So(o.Exec(a, b), convey.ShouldEqual, 6)
    o.SetStrategy(reduce)
    convey.So(o.Exec(a, b), convey.ShouldEqual, 2)
})