go 中的策略模式通过定义接口和不同策略类型来实现算法与使用者分离,从而实现代码复用:定义策略接口,包含一个方法来执行特定操作。创建不同的策略类型,实现接口中的方法并执行不同的算法。创建上下文对象,持有策略对象并调用其方法。
如何在 Go 框架中使用策略模式实现代码复用
策略模式简介
策略模式是一种设计模式,允许将算法的实现与算法的使用者分离。它提供了一种可插拔的方式来选择和使用不同的算法,而无需修改客户端代码。
立即学习“go语言免费学习笔记(深入)”;
Go 中的策略模式
在 Go 中,可以通过定义一个接口和一组实现该接口的不同类型的策略来实现策略模式。
接口定义
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)
}