parent
7d29259efb
commit
d664dd3934
@ -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…
Reference in new issue