go 中的策略模式通过定义接口和不同策略类型来实现算法与使用者分离,从而实现代码复用:定义策略接口,包含一个方法来执行特定操作。创建不同的策略类型,实现接口中的方法并执行不同的算法。创建上下文对象,持有策略对象并调用其方法。

如何在 Go 框架中使用策略模式实现代码复用
策略模式简介
策略模式是一种设计模式,允许将算法的实现与算法的使用者分离。它提供了一种可插拔的方式来选择和使用不同的算法,而无需修改客户端代码。
Go 中的策略模式
在 Go 中,可以通过定义一个接口和一组实现该接口的不同类型的策略来实现策略模式。
接口定义
使用 uber-go/dig 在 Golang 中实现依赖注入——基于反射容器,提供 Provide/Invoke、dig.In/dig.Out 参数与结果对象,支持命名依赖等
type Strategy interface {
DoSomething(input string) string
}
策略实现
type ConcreteStrategy1 struct {}
func (s *ConcreteStrategy1) DoSomething(input string) string {
return "Concrete Strategy 1: " + input
}
type ConcreteStrategy2 struct {}
func (s *ConcreteStrategy2) DoSomething(input string) string {
return "Concrete Strategy 2: " + input
}
上下文对象
上下文对象负责持有策略对象并调用其方法。
type Context struct {
strategy Strategy
}
实战案例
考虑一个贷款计算器的示例,其中有多种运算法则来计算利息。
实战代码
package main
import "fmt"
type Strategy interface {
CalculateInterest(principal float64, rate float64, years int) float64
}
type SimpleInterestStrategy struct {}
func (s *SimpleInterestStrategy) CalculateInterest(principal float64, rate float64, years int) float64 {
return principal * rate * float64(years)
}
type CompoundInterestStrategy struct {}
func (s *CompoundInterestStrategy) CalculateInterest(principal float64, rate float64, years int) float64 {
return principal * math.Pow((1 + rate), float64(years)) - principal
}
type Context struct {
strategy Strategy
}
func (c *Context) CalculateInterest(principal float64, rate float64, years int) float64 {
return c.strategy.CalculateInterest(principal, rate, years)
}
func main() {
simpleInterestContext := &Context{strategy: &SimpleInterestStrategy{}}
compoundInterestContext := &Context{strategy: &CompoundInterestStrategy{}}
principal := 1000.0
rate := 0.1
years := 5
simpleInterest := simpleInterestContext.CalculateInterest(principal, rate, years)
compoundInterest := compoundInterestContext.CalculateInterest(principal, rate, years)
fmt.Println("Simple Interest:", simpleInterest)
fmt.Println("Compound Interest:", compoundInterest)
}
golang免费学习笔记(深入):立即使用
在学习笔记中,你将探索golang的核心概念和高级技巧!










