赞
踩
策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
实现一个商场收银软件
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
}
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)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。