策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合[DPE]。
策略模式就是用来封装算法的,可以用它来封装几乎任何类型的规则,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性[DPE]。
策略模式的Strategy 类层次为Context定义了一系列的可供重用的算法或行为,继承有助于析取
出这些算法中的公共功能[DP]。
此模式让算法的变化,不会影响到使用算法的客户。
客户端需声明一个Context类,创建Strategy实例来初始化Strategy变量,由ContextInterface调用Strategy的AlgorithmInterface()。
与简单工厂模式结合时,只需识别Context类,并传入一定的参数,在Context内部根据参数来实例化不同的Strategy类,而后调用其算法实现AlgorithmInterface(),这种做法使得耦合更加降低。
type Strategy struct {
strategyType string
}
func (s* Strategy) GetStrategyType() string {
return s.strategyType
}
func (s* Strategy) SetStrategyType(strategyType string) {
// todo: params validation
s.strategyType = strategyType
}
// 待实现策略的接口
type StrategiesInterface interface {
Show()
}
// 具体策略1
type StrategyOne struct {
Strategy
}
func (s *StrategyOne) Show() {
s.SetStrategyType("Strategy One")
fmt.Println("Use strategy: "+s.GetStrategyType())
}
// 具体策略2
type StrategyTwo struct {
strategy.Strategy
}
func (s *StrategyTwo) Show() {
s.SetStrategyType("Strategy Two")
fmt.Println("Use strategy: "+s.GetStrategyType())
}
// 持有策略对象的上下文
type Context struct {
strategy StrategiesInterface
}
func (c *Context) SetStrategy(strategy StrategiesInterface) {
c.strategy = strategy
}
func (c* Context) Show() {
c.strategy.Show()
}
func main() {
context := Context{}
context.SetStrategy(&StrategyOne{})
context.Show()
context.SetStrategy(&StrategyTwo{})
context.Show()
}