Go 实现常用设计模式(二)策略模式

策略模式(strategy)

意图:
定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。

关键代码:
实现同一个接口

应用实例:

  1. 主题的更换,每个主题都是一种策略
  2. 旅行的出游方式,选择骑自行车、坐汽车,每一种旅行方式都是一个策略
  3. JAVA AWT 中的 LayoutManager

Go实现策略模式

package strategy

// 策略模式

// 实现此接口,则为一个策略
type IStrategy interface {
    do(int, int) int
}

// 加
type add struct{}

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

// 减
type reduce struct{}

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

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

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

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

测试用例

package strategy

import (
   "fmt"
 "testing")

func TestStrategy(t *testing.T) {
   operator := Operator{}

   operator.setStrategy(&add{})
   result := operator.calculate(1, 2)
   fmt.Println("add:", result)

   operator.setStrategy(&reduce{})
   result = operator.calculate(2, 1)
   fmt.Println("reduce:", result)
}

具体代码

更详细的代码可参考:https://github.com/pibigstar/go-demo 里面包含了 Go 常用的设计模式、Go 面试易错点、简单的小项目(区块链,爬虫等)、还有各种第三方的对接(redis、sms、nsq、elsticsearch、alipay、oss...),如果对你有所帮助,请给个 Star,你的支持,是我最大的动力!

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!