概念
策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
需求
实现一个商场收银软件
UML图
代码
所有策略的父接口
type CashSuper interface {
acceptCash(money float64) float64
}
正常收费策略
type CashNormal struct {
}
func (c *CashNormal) acceptCash(money float64) float64 {
return money
}
满减收费策略
type CashReturn struct {
moneyCondition float64
moneyReturn float64
}
func (c *CashReturn) acceptCash(money float64) float64 {
result := money
if money > c.moneyCondition {
result = result - math.Floor(money/c.moneyCondition)*c.moneyReturn
}
return result
}
打折收费策略
type CashRebate struct {
moneyRebate float64
}
func (c *CashRebate) acceptCash(money float64) float64 {
return money * c.moneyRebate
}
简单工厂封装构造CashContext的过程
type CashContext struct {
cs CashSuper
}
func (c *CashContext) CashContextFactory(typ string) CashContext {
switch typ {
case "正常收费":
c.cs = &CashNormal{}
case "满300返100":
c.cs = &CashReturn{moneyCondition: 300, moneyReturn: 100}
case "打8折":
c.cs = &CashRebate{moneyRebate: 0.8}
default:
panic("do not support")
}
return *c
}
func (c *CashContext) GetResult(money float64) float64 {
return c.cs.acceptCash(money)
}
测试
//策略模式 + 简单工厂模式
var cc strategyPattern.CashContext
cc = cc.CashContextFactory("满300返100")
result := cc.GetResult(1000)
fmt.Println(result)