模式定义

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

类图

要点总结

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

Go语言代码实现

工程目录


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() }