大话设计模式——策略与简单工厂结合

策略模式和简单工厂模式相结合,是通过将策略模式中由客户端承担的选择具体实现的职责转移到Context类中以减轻客户端职责,降低程序耦合度。

优势

降低了客户端和算法之间的耦合度。

劣势

在Context类中仍需实现选择具体实现的判断。

程序示例

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

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
50
51
52
53
54
# 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:
stratey = {}
stratey[1] = CashNormal()
stratey[2] = CashRebate(0.8)
stratey[3] = CashReturn(300, 100)
def __init__(self, cashType):
if cashType in self.stratey:
self.cs = self.stratey[cashType]
else:
raise Exception('cashType error.')

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

if __name__ == '__main__':
money = input(u'Money: ')
repeat = True
while repeat is True:
try:
cashType = input(u'1. Normal.\n2. Discount of twenty percent.\n3. Per more than $300 cashback $100.\nPay type: ')
csuper = CashContext(cashType)
print u'Amount Paid: %.2f' % csuper.GetResult(money)
repeat = False
except Exception:
print '\nPay type error.\n'