设计模式--策略(Strategy)模式

模式定义

定义一系列算法,把它们一个个封装起来,并且使它们可互相替换(变化),该模式使得算法可独立于使用它的客户程序(稳定)而变化(扩展,子类化)

类图

image-20210719214446705.png

要点总结

  • Strategy及其子类为组件提供了一系列可重用的算法,从而可以使得类型在运行时方便地根据需要在各个算法之间进行交换
  • Strategy模式提供了用条件判断语句以外的另一种选择,消除条件判断语句,就是解耦合。含有许多条件判断语句的代码通常都需要Strategy模式
  • 如果Strategy对象没有实例变量,那么各个上下文可以共享一个Strategy对象,从而节省对象开销

Go语言代码实现

工程目录

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-N7fDlqPO-1626705006764)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6d34aa329b7c4d359b25560947dfbce7~tplv-k3u1fbpfcp-watermark.image)]

image-20210705235128007.png
strategy.go

package Strategy

//策略接口
type Strategy interface {
   Execute()
}

strategyA.go

package Strategy

import "fmt"

//策略A
type strategyA struct {

}

//实现接口
func (s *strategyA) Execute(){
   fmt.Println("A plan executed.")
}

//简单工厂方法
func NewStrategyA() Strategy {
   return &strategyA{}
}

strategyB.go

package Strategy

import "fmt"

//策略B
type strategyB struct {

}

//实现接口
func (s *strategyB) Execute() {
   fmt.Println("B plan executed.")
}

//简单工厂方法
func NewStrategyB() Strategy {
   return &strategyB{}
}

context.go

package Strategy

//上下文,也可以理解为主逻辑
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()
}

strategy_test.go

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()
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值