首页 > 后端开发 > Golang > 正文

如何用Golang实现策略模式_Golang 策略模式实现实践

P粉602998670
发布: 2025-11-22 19:36:44
原创
326人浏览过
策略模式通过接口或函数封装不同算法,使算法可互换且符合开闭原则;以折扣计算为例,定义DiscountStrategy接口及多种会员折扣实现,Order上下文通过SetStrategy动态切换策略,调用GetFinalPrice获得不同折扣价;Golang中亦可用函数类型简化实现,定义DiscountFunc类型及对应函数,OrderFunc结构体接收函数式策略,实现更简洁的动态替换;该模式适用于支付方式、排序算法等需运行时切换行为的场景,避免多重条件判断,提升扩展性与维护性。

如何用golang实现策略模式_golang 策略模式实现实践

策略模式是一种行为设计模式,它让你定义一系列算法或行为,并将它们封装在独立的类或结构体中,使得它们可以互相替换。在 Golang 中虽然没有类的概念,但通过接口和函数式编程特性,我们可以很自然地实现策略模式。

策略模式的核心思想

将不同的“策略”(即算法)抽象为统一接口,客户端通过该接口调用具体策略,而无需关心内部实现。当需要更换算法时,只需更换策略实例,不修改原有代码,符合开闭原则。

比如:支付方式、排序算法、日志输出格式等场景都适合使用策略模式。

使用接口实现策略模式

假设我们有一个任务是计算订单折扣,不同会员等级有不同的折扣策略。

立即学习go语言免费学习笔记(深入)”;

定义策略接口:

type DiscountStrategy interface {
    CalculateDiscount(amount float64) float64
}
登录后复制

实现具体策略:

type NormalUserStrategy struct{}
<p>func (s <em>NormalUserStrategy) CalculateDiscount(amount float64) float64 {
return amount </em> 0.05 // 5% 折扣
}</p><p>type VipUserStrategy struct{}</p><p>func (s <em>VipUserStrategy) CalculateDiscount(amount float64) float64 {
return amount </em> 0.15 // 15% 折扣
}</p><p>type PremiumUserStrategy struct{}</p><p>func (s <em>PremiumUserStrategy) CalculateDiscount(amount float64) float64 {
return amount </em> 0.30 // 30% 折扣
}
登录后复制

上下文使用策略:

Northstar盈富量化交易软件
Northstar盈富量化交易软件

Northstar盈富量化交易软件是一个基于B/S架构的一站式量化交易平台,能进行历史回放、策略研发、模拟交易、实盘交易。 已对接国内期货CTP交易系统,并陆续补充国内股票XTP渠道、老虎证券、币安等多种渠道。这是一个面向程序员的开源高频量化交易软件,用于期货、股票、外汇、炒币等多种交易场景,实现自动交易。暂时只对接了国内期货交易所,理论上可以对接任意交易所。 功能特性:1、一站式平台,可适配对接

Northstar盈富量化交易软件 34
查看详情 Northstar盈富量化交易软件

type Order struct {
    Amount   float64
    Strategy DiscountStrategy
}
<p>func (o *Order) SetStrategy(strategy DiscountStrategy) {
o.Strategy = strategy
}</p><p>func (o *Order) GetFinalPrice() float64 {
discount := o.Strategy.CalculateDiscount(o.Amount)
return o.Amount - discount
}
登录后复制

使用示例:

order := &Order{Amount: 100}
<p>order.SetStrategy(&NormalUserStrategy{})
fmt.Printf("普通用户最终价格: %.2f\n", order.GetFinalPrice()) // 95.00</p><p>order.SetStrategy(&VipUserStrategy{})
fmt.Printf("VIP用户最终价格: %.2f\n", order.GetFinalPrice()) // 85.00</p><p>order.SetStrategy(&PremiumUserStrategy{})
fmt.Printf("高级用户最终价格: %.2f\n", order.GetFinalPrice()) // 70.00
登录后复制

使用函数式风格简化策略模式

Golang 支持函数作为一等公民,我们可以用函数替代接口,使代码更简洁。

定义函数类型作为策略:

type DiscountFunc func(amount float64) float64
登录后复制

实现不同策略函数:

func NormalDiscount(amount float64) float64 {
    return amount * 0.05
}
<p>func VipDiscount(amount float64) float64 {
return amount * 0.15
}</p><p>func PremiumDiscount(amount float64) float64 {
return amount * 0.30
}
登录后复制

更新上下文以接受函数:

type OrderFunc struct {
    Amount   float64
    Strategy DiscountFunc
}
<p>func (o *OrderFunc) SetStrategy(f DiscountFunc) {
o.Strategy = f
}</p><p>func (o *OrderFunc) GetFinalPrice() float64 {
if o.Strategy != nil {
discount := o.Strategy(o.Amount)
return o.Amount - discount
}
return o.Amount
}
登录后复制

调用方式类似:

orderFunc := &OrderFunc{Amount: 100}
orderFunc.SetStrategy(NormalDiscount)
fmt.Printf("函数式-普通用户: %.2f\n", orderFunc.GetFinalPrice())
登录后复制

适用场景与优势

策略模式适用于以下情况:

  • 有多个相似类,仅行为不同
  • 需要在运行时动态切换算法
  • 避免使用多重条件判断(如 if-else 或 switch)选择行为

优势包括:

  • 算法可自由切换
  • 扩展性强,新增策略不影响现有代码
  • 职责清晰,每种策略独立封装

基本上就这些。Golang 虽无继承,但通过接口和函数式编程能优雅实现策略模式,关键是把变化的行为抽象出来,让调用方只依赖抽象,不依赖具体实现。

以上就是如何用Golang实现策略模式_Golang 策略模式实现实践的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号