大话设计模式——策略模式

策略模式的核心思想是定义一个算法家族并分别封装起来,这些算法都完成相同的功能,只是实现不同,通过策略模式的封装可以使算法之间互相替换并且不影响到客户端。

优势

适用于以方法为主,算法经常变动的类;每个算法都有自己的类,简化了测试单元。

劣势

需要客户端参与判断初始化对象类型。

UML类图

程序示例

商场收银软件,可以根据不同销售策略进行收费。

UML类图

Python代码

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
47
48
49
# coding: utf-8

class CashSuper:
def acceptCash(self, money):
pass

class CashNormal(CashSuper):
def acceptCash(self, money):
return money

class CashRebate(CashSuper):
def __init__(self, moneyRebate):
self.moneyRebate = moneyRebate

def acceptCash(self, money):
return money * self.moneyRebate

class CashReturn(CashSuper):
def __init__(self, moneyCondition, moneyReturn):
self.moneyCondition = moneyCondition
self.moneyReturn = moneyReturn

def acceptCash(self, money):
result = money
if money >= self.moneyCondition:
result = money - (int(money / self.moneyCondition) * self.moneyReturn)
return result

class CashContext:
def __init__(self, csuper):
self.cs = csuper

def GetResult(self, money):
return self.cs.acceptCash(money)

if __name__ == '__main__':
money = input(u'Money: ')
stratey = {}
stratey[1] = CashContext(CashNormal())
stratey[2] = CashContext(CashRebate(0.8))
stratey[3] = CashContext(CashReturn(300, 100))
cashType = None
while cashType not in stratey:
cashType = input(u'1. Normal.\n2. Discount of twenty percent.\n3. Per more than $300 cashback $100.\nPay type: ')
if cashType in stratey:
print cashType
print u'Amount Paid: %.2f' % stratey[cashType].GetResult(money)
else:
print u'Pay type error.\n'