美文网首页
strategy in go

strategy in go

作者: 将军红 | 来源:发表于2019-12-19 16:55 被阅读0次
package disign

import "fmt"

// 接口
type cashSuper interface {
    AcceptMoney(money float64) float64
}

//1普通情况,没有折扣
type cashNormal struct {}

func newCashNormal() cashNormal {
    instance := new(cashNormal)
    return *instance
}

func (c cashNormal) AcceptMoney(money float64) float64 {
    return money
}

//2打折,传入打折的折扣,如0.8
type cashRebate struct {
    Rebate float64 //折扣
}

func newCashRebate(rebate float64) cashRebate {
    instance := new(cashRebate)
    instance.Rebate = rebate
    return *instance
}

func (c cashRebate) AcceptMoney(money float64) float64 {
    return money * c.Rebate
}

//3直接返利,如满100返20
type cashReturn struct {
    MoneyCondition float64
    MoneyReturn    float64
}

func newCashReturn(moneyCondition float64, moneyReturn float64) cashReturn {
    instance := new(cashReturn)
    instance.MoneyCondition = moneyCondition
    instance.MoneyReturn = moneyReturn
    return *instance
}

func (c cashReturn) AcceptMoney(money float64) float64 {
    if money >= c.MoneyCondition {
        moneyMinus := int(money / c.MoneyCondition)
        return money - float64(moneyMinus)*c.MoneyReturn
    }
    return money
}


//最重要的时刻来临了,定义CashContext结构,用来做策略筛选
type CashContext struct {
    Strategy cashSuper //定义Strategy是接口cashSuper类型 [核心]
}

func (c CashContext) GetMoney(money float64) float64 {
    return c.Strategy.AcceptMoney(money)
}

func NewCashContext(cashType string) CashContext {
    c := new(CashContext)
    //这里事实上是简易工厂模式的变形,用来生产策略
    switch cashType {
    case "打八折":
        c.Strategy = newCashRebate(0.8)
    case "满一百返20":
        c.Strategy = newCashReturn(100.0, 20.0)
    default:
        c.Strategy = newCashNormal()
    }
    return *c
}

func main() {
    //测试用例
    money := 100.0
    cc := NewCashContext("打八折")
    money = cc.GetMoney(money)
    fmt.Println("100打八折实际金额为", money)

    money = 199
    cc = NewCashContext("满一百返20")
    money = cc.GetMoney(money)
    fmt.Println("199满一百返20实际金额为", money)

    money = 199
    cc = NewCashContext("没有折扣")
    money = cc.GetMoney(money)
    fmt.Println("199没有折扣实际金额为", money)

}

相关文章

网友评论

      本文标题:strategy in go

      本文链接:https://www.haomeiwen.com/subject/wlfvnctx.html