策略模式通过接口定义行为,使算法独立实现并动态切换。首先定义DiscountStrategy接口,包含Apply方法;接着创建NoDiscount、PercentageDiscount和FixedDiscount结构体实现该接口,分别表示无折扣、百分比折扣和固定金额折扣;然后使用PriceCalculator上下文管理策略,通过SetStrategy方法切换策略,并调用CalculateFinalPrice执行计算;最终实现代码解耦,提升可维护性与扩展性,适用于多种行为变体且需运行时切换的场景。

在Golang中实现策略模式,核心是通过接口定义行为,让不同算法以独立结构体形式实现该接口,从而实现运行时动态切换算法。这种方式避免了使用大量条件判断语句,提升代码可维护性和扩展性。
策略模式的第一步是定义一个公共接口,用于声明所有具体策略必须实现的方法。例如,在处理不同排序算法或计算折扣策略时,可以抽象出统一行为。
type DiscountStrategy interface {
Apply(amount float64) float64
}这个接口规定了所有折扣策略都需要有一个 Apply 方法,接收原金额并返回折后金额。
接下来编写多个结构体来实现上述接口,每个结构体代表一种具体的算法逻辑。
立即学习“go语言免费学习笔记(深入)”;
type NoDiscount struct{}
<p>func (n *NoDiscount) Apply(amount float64) float64 {
return amount
}</p><p>type PercentageDiscount struct {
Rate float64
}</p><p>func (p <em>PercentageDiscount) Apply(amount float64) float64 {
return amount </em> (1 - p.Rate)
}</p><p>type FixedDiscount struct {
Amount float64
}</p><p>func (f *FixedDiscount) Apply(amount float64) float64 {
if amount <= f.Amount {
return 0
}
return amount - f.Amount
}每种折扣方式封装在独立类型中,调用方无需了解内部细节,只需调用 Apply 方法即可。
创建一个上下文结构体持有当前策略,并提供方法用于切换和执行策略。
type PriceCalculator struct {
strategy DiscountStrategy
}
<p>func (c *PriceCalculator) SetStrategy(s DiscountStrategy) {
c.strategy = s
}</p><p>func (c *PriceCalculator) CalculateFinalPrice(amount float64) float64 {
if c.strategy == nil {
panic("no strategy set")
}
return c.strategy.Apply(amount)
}这样可以在运行时根据业务条件灵活更换策略:
calc := &PriceCalculator{}
calc.SetStrategy(&PercentageDiscount{Rate: 0.1}) // 10% 折扣
fmt.Println(calc.CalculateFinalPrice(100)) // 输出 90
<p>calc.SetStrategy(&FixedDiscount{Amount: 20})
fmt.Println(calc.CalculateFinalPrice(100)) // 输出 80策略模式将算法与使用逻辑解耦,适用于以下情况:
基本上就这些,不复杂但容易忽略的是接口抽象的粒度控制——太粗会限制灵活性,太细则增加管理成本。
以上就是如何在Golang中实现策略模式_Golang策略模式算法切换方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号