大话设计模式Python实现-策略模式

策略模式(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,定义一个上下文管理类,接收一个策略,并根据该策略得出结论,当需要更改策略时,只需要在实例的时候传入不同的策略就可以,免去了修改类的麻烦

 

 

 


作者:Andy
出处:http://www.cnblogs.com/onepiece-andy/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

posted @ 2017-10-30 11:28  Andy冉明  阅读(7882)  评论(1编辑  收藏  举报