策略模式(Strategy Pattern):它定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户.
1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 __author__ = ‘Andy‘
5 ‘‘‘
6 大话设计模式
7 设计模式——策略模式
8 策略模式(strategy):它定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户
9 ‘‘‘
10
11 #现金收费抽象类
12 class CashSuper(object):
13
14 def accept_cash(self,money):
15 pass
16 #正常收费子类
17 class CashNormal(CashSuper):
18
19 def accept_cash(self,money):
20 return money
21
22 #打折收费子类
23 class CashRebate(CashSuper):
24
25 def __init__(self,discount=1):
26 self.discount = discount
27
28 def accept_cash(self,money):
29 return money * self.discount
30
31 #返利收费子类
32 class CashReturn(CashSuper):
33
34 def __init__(self,money_cOndition=0,money_return=0):
35 self.money_cOndition= money_condition
36 self.money_return = money_return
37
38 def accept_cash(self,money):
39 if money>=self.money_condition:
40 return money - (money / self.money_condition) * self.money_return
41 return money
42
43 #具体策略类
44 class Context(object):
45
46 def __init__(self,csuper):
47 self.csuper = csuper
48
49 def GetResult(self,money):
50 return self.csuper.accept_cash(money)
51
52
53
54
55 if __name__ == ‘__main__‘:
56 mOney= input("原价: ")
57 strategy = {}
58 strategy[1] = Context(CashNormal())
59 strategy[2] = Context(CashRebate(0.8))
60 strategy[3] = Context(CashReturn(100,10))
61 mode = input("选择折扣方式: 1) 原价 2) 8折 3) 满100减10: ")
62 if mode in strategy:
63 csuper = strategy[mode]
64 else:
65 print "不存在的折扣方式"
66 csuper = strategy[1]
67 print "需要支付: ",csuper.GetResult(money)
使用一个策略类CashSuper定义需要的算法的公共接口,定义三个具体策略类:CashNormal,CashRebate,CashReturn,继承于CashSuper,定义一个上下文管理类,接收一个策略,并根据该策略得出结论,当需要更改策略时,只需要在实例的时候传入不同的策略就可以,免去了修改类的麻烦