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

Golang如何实现策略模式替换条件逻辑

P粉602998670
发布: 2025-10-15 17:29:01
原创
490人浏览过
策略模式通过接口抽象行为,用结构体实现不同策略,借助上下文动态切换,避免冗长条件判断。定义DiscountStrategy接口及多种折扣实现,如NormalDiscount、VIPDiscount等,再通过PriceCalculator持有策略并执行计算。根据用户类型从预注册的map中获取对应策略,实现灵活扩展与开闭原则,提升代码可维护性。

golang如何实现策略模式替换条件逻辑

在 Go 语言中,策略模式能有效替代冗长的 if-elseswitch-case 条件判断,提升代码的可维护性和扩展性。当你有一组相似行为、需要根据不同类型动态选择执行方式时,策略模式是一个理想选择。

定义统一的行为接口

策略模式的核心是抽象出一个公共接口,所有具体策略都实现这个接口。例如,假设我们要根据不同的折扣类型计算价格:

type DiscountStrategy interface {
    Apply(price float64) float64
}
登录后复制

实现多种具体策略

每种折扣方式作为一个独立结构体实现接口,比如普通会员、VIP 会员、超级 VIP 折扣:

type NormalDiscount struct{}
<p>func (d <em>NormalDiscount) Apply(price float64) float64 {
return price </em> 0.95 // 95折
}</p><p>type VIPDiscount struct{}</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">go语言免费学习笔记(深入)</a>”;</p><p>func (d <em>VIPDiscount) Apply(price float64) float64 {
return price </em> 0.9 // 9折
}</p><p>type SuperVIPDiscount struct{}</p>
                    <div class="aritcle_card">
                        <a class="aritcle_card_img" href="/ai/%E6%A8%A1%E5%8A%9B%E8%A7%86%E9%A2%91">
                            <img src="https://img.php.cn/upload/ai_manual/001/246/273/68b6db5f7537e305.png" alt="模力视频">
                        </a>
                        <div class="aritcle_card_info">
                            <a href="/ai/%E6%A8%A1%E5%8A%9B%E8%A7%86%E9%A2%91">模力视频</a>
                            <p>模力视频 - AIGC视频制作平台 | AI剪辑 | 云剪辑 | 海量模板</p>
                            <div class="">
                                <img src="/static/images/card_xiazai.png" alt="模力视频">
                                <span>51</span>
                            </div>
                        </div>
                        <a href="/ai/%E6%A8%A1%E5%8A%9B%E8%A7%86%E9%A2%91" class="aritcle_card_btn">
                            <span>查看详情</span>
                            <img src="/static/images/cardxiayige-3.png" alt="模力视频">
                        </a>
                    </div>
                <p>func (d <em>SuperVIPDiscount) Apply(price float64) float64 {
return price </em> 0.8 // 8折
}</p>
登录后复制

使用策略上下文动态切换逻辑

创建一个上下文结构体来持有当前策略,并提供设置和执行方法:

type PriceCalculator struct {
    strategy DiscountStrategy
}
<p>func (c *PriceCalculator) SetStrategy(s DiscountStrategy) {
c.strategy = s
}</p><p>func (c *PriceCalculator) Calculate(price float64) float64 {
if c.strategy == nil {
panic("未设置策略")
}
return c.strategy.Apply(price)
}</p>
登录后复制

调用时根据用户类型切换策略,不再使用条件判断:

calculator := &PriceCalculator{}
<p>// 模拟不同用户
var strategy DiscountStrategy
switch userType {
case "normal":
strategy = &NormalDiscount{}
case "vip":
strategy = &VIPDiscount{}
case "super_vip":
strategy = &SuperVIPDiscount{}
default:
strategy = &NormalDiscount{}
}</p><p>calculator.SetStrategy(strategy)
finalPrice := calculator.Calculate(100)</p>
登录后复制

更进一步,可以将类型到策略的映射预先注册,彻底消除条件分支:

var strategies = map[string]DiscountStrategy{
    "normal":     &NormalDiscount{},
    "vip":        &VIPDiscount{},
    "super_vip":  &SuperVIPDiscount{},
}
<p>// 使用时直接获取
if strategy, ok := strategies[userType]; ok {
calculator.SetStrategy(strategy)
}</p>
登录后复制

这样,新增折扣类型只需添加新结构体并注册到 map,无需修改已有逻辑,符合开闭原则。

基本上就这些。用接口抽象行为,通过注入不同实现来替换条件判断,Go 虽无继承,但组合和接口让策略模式依然简洁有力。关键是避免在业务中散落一堆 if-else,把变化封装起来。

以上就是Golang如何实现策略模式替换条件逻辑的详细内容,更多请关注php中文网其它相关文章!

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

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

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

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