feat: add strategy

main
ZGGSONG 2 years ago
parent 7d29259efb
commit d664dd3934

@ -6,9 +6,9 @@ func CreateCashAccept(t int) Casher {
case 1: //正常
cash = new(CashNormal)
case 2: //8折
cash = &CashRebate{moneyRebate: 0.8}
cash = &CashRebate{MoneyRebate: 0.8}
case 3: //满300减50
cash = &CashReturn{moneyCondition: 300, moneyReturn: 50}
cash = &CashReturn{MoneyCondition: 300, MoneyReturn: 50}
default:
}
return cash

@ -3,9 +3,9 @@ package factory
// CashRebate
// @Description: 打折收费
type CashRebate struct {
moneyRebate float64
MoneyRebate float64
}
func (c *CashRebate) AcceptCash(money float64) float64 {
return money * c.moneyRebate
return money * c.MoneyRebate
}

@ -5,14 +5,14 @@ import "math"
// CashReturn
// @Description: 返利收费
type CashReturn struct {
moneyCondition float64
moneyReturn float64
MoneyCondition float64
MoneyReturn float64
}
func (c *CashReturn) AcceptCash(money float64) float64 {
ret := money
if money >= c.moneyCondition {
ret = money - math.Floor(money/c.moneyCondition)*c.moneyReturn
if money >= c.MoneyCondition {
ret = money - math.Floor(money/c.MoneyCondition)*c.MoneyReturn
}
return ret
}

@ -0,0 +1,3 @@
策略模式
"因为,当不同的行为堆砌在一个类中时,就很难避免使用条件语句来选择合适的行为。将这些行为封装在一个个独立的 Strategy 类中,可以在使用这些行为的类中消除条件语句。"---《大话设计模式》

@ -0,0 +1,11 @@
package strategy
import "designpatterns/factory"
type CashContext struct {
cash factory.Casher
}
func (c CashContext) GetResponse(money float64) float64 {
return c.cash.AcceptCash(money)
}

@ -0,0 +1,23 @@
package strategy
import "designpatterns/factory"
type CashFactoryStrategyContext struct {
d int
cashFactoryStrategy factory.Casher
}
func (c *CashFactoryStrategyContext) GetCash() {
switch c.d {
case 1:
c.cashFactoryStrategy = &factory.CashNormal{}
case 2:
c.cashFactoryStrategy = &factory.CashRebate{MoneyRebate: 0.8}
case 3:
c.cashFactoryStrategy = &factory.CashReturn{MoneyReturn: 5, MoneyCondition: 100}
}
}
func (c *CashFactoryStrategyContext) GetResult(money float64) float64 {
return c.cashFactoryStrategy.AcceptCash(money)
}

@ -0,0 +1,12 @@
package strategy
import (
"testing"
)
func TestCashFactoryContext_GetCash(t *testing.T) {
var data = &CashFactoryStrategyContext{d: 3}
data.GetCash()
result := data.GetResult(500)
t.Log(result)
}

@ -0,0 +1,20 @@
package strategy
import (
"designpatterns/factory"
"testing"
)
func TestCashContext_GetCash(t *testing.T) {
var cash CashContext
a := 2
switch a {
case 1:
cash = CashContext{cash: &factory.CashNormal{}}
case 2:
cash = CashContext{&factory.CashRebate{MoneyRebate: 0.99}}
case 3:
cash = CashContext{&factory.CashReturn{MoneyReturn: 100, MoneyCondition: 600}}
}
t.Log(cash.GetResponse(600))
}
Loading…
Cancel
Save