本文主要说一下设计模式之策略模式,后续会有更多的模式和算法以及区块链相关的,如果你是想学习go语言或者是对设计模式或者算法感兴趣亦或是区块链开发工作者,都可以关注一下。(微信公众号:Go语言之美,csdn:Go语言之美。更多go语言知识信息等)。
github(go语言算法、设计模式等持续更新):
https://github.com/rayyyes
![4ec57e7d1e24aec9af0adb60c325a5e6.png](https://i-blog.csdnimg.cn/blog_migrate/e0b34c9ae8a26858c1e9654c5802f6dc.jpeg)
商场打折是CRM系统中最常见的情况,商场随时会增加或者删除促销方式,而且促销方式非常多,我们需要针对各种情况做出不同的结果,例如打八折,我们就要根据实际价格计算出打八折的结果,满300返100等等。这个时候我们怎么做呢,大多数人没有接触设计模式时,都会想,只要用一个switch case语句就可以,其实这样确实可以,也能达到想要的结果,但是如果规则变得复杂了,增加和很多或者删除了很多,这样我们就很难维护了,如果有一百种促销方式,难道我们要在一百个case语句里写上各个算法吗?这样维护起来贼难受,所以我们就有了策略模式。
![a944d50303ba1c3a6111769134ad4413.png](https://i-blog.csdnimg.cn/blog_migrate/fefadcb40644aae8804e30f507f82a61.jpeg)
定义:策略模式定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
接下来我们实现一个小的商场促销模式,分别是正常收费,打八折和满300返100的撤销方法。
package mainimport "fmt"type CashSuper interface { AcceptCash(money float64) float64}// 正常收费type Normal struct {}func (this *Normal) AcceptCash(money float64) float64 { return money}// 打折type CashRebate struct { Rebate float64}func (this *CashRebate) SetRebate(rebate float64) { this.Rebate = rebate}func (this *CashRebate) AcceptCash(money float64) float64 { return this.Rebate * money}// 满 x 返 ytype CashReturn struct { MoneyCondition float64 MoneyReturn float64}func (this *CashReturn) SetCashReturn(moneyCondition float64, moneyReturn float64) { this.MoneyCondition = moneyCondition this.MoneyReturn = moneyReturn}func (this *CashReturn) AcceptCash(money float64) float64 { if money >= this.MoneyCondition { moneyMinus := int(money / this.MoneyCondition) return money - float64(moneyMinus)*this.MoneyReturn } return money}type CashContext struct { Strategy CashSuper}func (this *CashContext) SetCashContext(t string) { switch t { case "正常收费": normal := new(Normal) this.Strategy = normal case "打八折": r := new(CashRebate) r.SetRebate(0.8) this.Strategy = r case "满300返100": r := new(CashReturn) r.SetCashReturn(300, 100) this.Strategy = r }}func (this *CashContext) GetMoney(money float64) float64 { return this.Strategy.AcceptCash(money)}func main() { cs := new(CashContext) cs.SetCashContext("打八折") result := cs.GetMoney(100) fmt.Println("100元打八折结果: