go-pattern-examples/behavior/12_strategy/strategy.go

55 lines
1.3 KiB
Go
Raw Normal View History

2020-04-21 17:50:21 +03:00
package strategy
import "fmt"
2020-04-28 09:43:37 +03:00
//money kind
const (
RMB = "RMB"
HK = "HK"
)
//StoreContext for Store 要包存钱的上下文信息
type StoreContext struct {
Kind, CardID string
2020-04-21 17:50:21 +03:00
Money int
}
2020-04-28 09:43:37 +03:00
//IStore 要实现的存钱接口
type IStore interface {
Store(*StoreContext)
2020-04-21 17:50:21 +03:00
}
2020-04-28 09:43:37 +03:00
//MainLandCitizen 大陆居民
type MainLandCitizen struct{ Name string }
2020-04-21 17:50:21 +03:00
2020-04-28 09:43:37 +03:00
//Store Money to bank
func (m *MainLandCitizen) Store(ctx *StoreContext) {
fmt.Println("i am: ", m.Name, "i want to store: ", ctx.Money, ctx.Kind, "to: ", ctx.CardID)
2020-04-21 17:50:21 +03:00
}
2020-04-28 09:43:37 +03:00
//HongKongCitizen 香港居民
type HongKongCitizen struct{ Name string }
2020-04-21 17:50:21 +03:00
2020-04-28 09:43:37 +03:00
//Store Money to bank
func (h *HongKongCitizen) Store(ctx *StoreContext) {
fmt.Println("i am: ", h.Name, "i want to store: ", ctx.Money, ctx.Kind, "to: ", ctx.CardID)
2020-04-21 17:50:21 +03:00
}
2020-04-28 09:43:37 +03:00
//Bank handle moneyholder
type Bank struct {
moneyHolder IStore
}
2020-04-21 17:50:21 +03:00
2020-04-28 09:43:37 +03:00
//Recept a user
func (b *Bank) Recept(moneyHolder IStore) {
b.moneyHolder = moneyHolder
fmt.Println("Bank: ", "Recept a New User")
}
2020-04-21 17:50:21 +03:00
2020-04-28 09:43:37 +03:00
//AccountUserMoney 动态替换的过程在这里,这里调用任何实现了Store的接口对象
//AccountUserMoney to handle User's Money
func (b *Bank) AccountUserMoney(ctx *StoreContext) {
b.moneyHolder.Store(ctx)
fmt.Println("Bank: ", "Processing Store", ctx.Money, ctx.Kind, "to: ", ctx.CardID)
2020-04-21 17:50:21 +03:00
}