通过接口定义行为并由不同结构体实现,Golang中策略模式可动态切换支付方式,避免条件判断,提升扩展性。

在Golang中实现策略模式,核心是通过接口定义行为,让不同策略结构体实现该接口,从而在运行时动态切换具体行为。这种方式避免了大量条件判断,提升了代码的可扩展性和可维护性。
先定义一个统一的行为接口,所有具体策略都需实现它。比如处理支付方式的场景:
<pre class="brush:php;toolbar:false;">type PaymentStrategy interface {
Pay(amount float64) string
}
不同的支付方式作为独立结构体实现接口。每个策略封装自己的逻辑:
<code>type C<a style="color:#f60; text-decoration:underline;" title="red" href="https://www.php.cn/zt/122037.html" target="_blank">red</a>itCardPayment struct{}
func (c *CreditCardPayment) Pay(amount float64) string {
return fmt.Sprintf("P<a style="color:#f60; text-decoration:underline;" title="ai" href="https://www.php.cn/zt/17539.html" target="_blank">ai</a>d %.2f using Credit Card", amount)
}
type PayPalPayment struct{}
func (p *PayPalPayment) Pay(amount float64) string {
return fmt.Sprintf("Paid %.2f via PayPal", amount)
}
type CryptoPayment struct{}
func (c *CryptoPayment) Pay(amount float64) string {
return fmt.Sprintf("Paid %.2f in Bitcoin", amount)
}
</code>使用一个上下文结构体持有当前策略,并提供方法更换策略。调用时只需执行当前策略的逻辑:
立即学习“go语言免费学习笔记(深入)”;
<code>type PaymentContext struct {
strategy PaymentStrategy
}
func (p *PaymentContext) SetStrategy(strategy PaymentStrategy) {
p.strategy = strategy
}
func (p *PaymentContext) ExecutePayment(amount float64) string {
if p.strategy == nil {
return "No strategy set"
}
return p.strategy.Pay(amount)
}
</code>使用示例:
<code>context := &PaymentContext{}
context.SetStrategy(&CreditCardPayment{})
fmt.Println(context.ExecutePayment(100.0)) // 输出:Paid 100.00 using Credit Card
context.SetStrategy(&PayPalPayment{})
fmt.Println(context.ExecutePayment(200.0)) // 输出:Paid 200.00 via PayPal
</code>这样就能在不修改调用代码的前提下,灵活替换行为。新增支付方式也只需添加新结构体并实现接口,完全符合开闭原则。
基本上就这些,关键是把变化的行为抽象成接口,再通过组合的方式注入到上下文中。
以上就是如何在Golang中实现策略模式动态切换行为的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号