大话设计模式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/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 想让你多爱自己一些的开源计时器
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析