关于设计模式:设计模式策略Strategy模式

28次阅读

共计 1284 个字符,预计需要花费 4 分钟才能阅读完成。

模式定义

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

类图

要点总结

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

正文完
 0