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

策略模式

优点

  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观察者模式

posted @ 2021-09-25 15:26  cheems~  阅读(100)  评论(0编辑  收藏  举报