Golang设计模式——15策略模式

策略模式允许在运行时选择不同的算法或行为,实现了开闭原则,简化了算法管理并避免了条件转移语句。通过创建一系列策略类,如出行方式或会员等级,客户端可以根据需要选择合适的行为。在代码示例中,展示了如何创建和切换策略。这种模式在需要动态改变行为或算法族管理的场景中非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

策略模式

优点

  1. 策略模式提供了对“开闭原则”的完美支持,用户可以在不修改原有系统的基础上选择算法或行为,也可以灵活地-增加新的算法或行为。
  2. 提供管理相关的算法族
  3. 可以替换继承关系的办法。
  4. 避免使用多重条件转移语句。
  5. 定义一系列算法,将每个算法封装起来。并让它们能够相互替换。策略模式让算法独立于使用它的客户而变化。

缺点

  1. 客户端必须知道所有的策略类,并自行决定使用哪一个策略类
  2. 策略模式将造成产生很多策略类,可以通过使用享元模式在一定程度上减少对象的数量

场景

  1. 张三从广东去北京【1.坐飞机,2.坐火车,3.走路】
  2. 鹅厂推出了3种会员,分别为会员,超级会员、黑钻会员

代码

package Strategy

import "fmt"

type Strategy interface {
	Execute()
}

type strategyA struct {
}

func NewStrategyA() Strategy {
	return &strategyA{}
}

func (s *strategyA) Execute() {
	fmt.Println("A plan executed.")
}

type strategyB struct {
}

func (s *strategyB) Execute() {
	fmt.Println("B plan executed.")
}

func NewStrategyB() Strategy {
	return &strategyB{}
}

type Context struct {
	strategy Strategy
}

func NewContext() *Context {
	return &Context{}
}

func (c *Context) SetStrategy(strategy Strategy) {
	c.strategy = strategy
}

func (c *Context) Execute() {
	c.strategy.Execute()
}

package Strategy

import "testing"

func TestContext_Execute(t *testing.T) {
	strategyA := NewStrategyA()
	c := NewContext()
	c.SetStrategy(strategyA)
	c.Execute()
	strategyB := NewStrategyB()
	c.SetStrategy(strategyB)
	c.Execute()
}

其他设计模式

设计模式Git源代码
00简单工厂模式
01工厂方法模式
02抽象工厂模式
03外观模式
04建造者模式
05桥接模式
06命令模式
07迭代器模式
08模板模式
09访问者模式
10备忘录模式
11责任链模式
12中介模式
13原型模式
14状态模式
15策略模式
16享元模式
17组合模式
18解释器模式
19单例模式
20适配器模式
21代理模式
22装饰器模式
23观察者模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cheems~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值