概述

策略模式定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户

使用场景

需要有一系列不同的算法,这些算法完成的工作是同样的,只是实现不同,强调以相同的方式调用所有的算法,减少算法类和使用算法类之间的耦合

优势

使代码结构清晰,便于维护,简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试 每个算法的修改都不会影响到其他的算法

实际应用场景

商场商品价格计算,其中涉及到的有商品的单价,个数,折扣 折扣的策略有:

  • 固定折扣
  • 满减

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
type CashSuper interface {
Accept(float64) float64
}
//CashNormal normal strategy
type CashNormal struct{}
func (normal CashNormal) Accept(money float64) float64 {
return money
}
//CashRebate
type CashRebate struct {
moneyRebate float64
}
func (re CashRebate) Accept(money float64) float64 {
return money * re.moneyRebate
}
//CashReturn
type CashReturn struct {
moneyCondition float64
moneyReturn float64
}
func (re CashReturn) Accept(money float64) float64 {
if money >= re.moneyCondition {
return money - re.moneyReturn
}
return money
}

type CashContext struct {
strategy CashSuper
}
func NewCashContext(acceptType string) (cashFactory CashContext) {
switch acceptType {
default:
fmt.Println("wrong type")
case "normal":
cashFactory.strategy = CashNormal{}
case "0.8rebate":
cashFactory.strategy = CashRebate{moneyRebate: 0.8}
case "300return100":
cashFactory.strategy = CashReturn{300, 100}
}
return
}
func (cashFactory CashContext) Accept(money float64) float64 {
return cashFactory.strategy.Accept(money)
}

Copyright © Ywnline 版权所有 冀ICP备20005992号-1