模式定义
定义一系列算法,把它们一个个封装起来,并且使它们可互相替换(变化),该模式使得算法可独立于使用它的客户程序(稳定)而变化(扩展,子类化)
类图
要点总结
- Strategy及其子类为组件提供了一系列可重用的算法,从而可以使得类型在运行时方便地根据需要在各个算法之间进行交换
- Strategy模式提供了用条件判断语句以外的另一种选择,消除条件判断语句,就是解耦合。含有许多条件判断语句的代码通常都需要Strategy模式
- 如果Strategy对象没有实例变量,那么各个上下文可以共享一个Strategy对象,从而节省对象开销
Go语言代码实现
工程目录
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-N7fDlqPO-1626705006764)(https://p1-juejin.byteimg.com...]
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()
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。