策略模式(Strategy Pattern):它定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户.

下面是一个商场活动的实现

 #!/usr/bin/env python
# -*- coding:utf-8 -*- __author__ = 'Andy'
'''
大话设计模式
设计模式——策略模式
策略模式(strategy):它定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户
''' #现金收费抽象类
class CashSuper(object): def accept_cash(self,money):
pass
#正常收费子类
class CashNormal(CashSuper): def accept_cash(self,money):
return money #打折收费子类
class CashRebate(CashSuper): def __init__(self,discount=1):
self.discount = discount def accept_cash(self,money):
return money * self.discount #返利收费子类
class CashReturn(CashSuper): def __init__(self,money_condition=0,money_return=0):
self.money_condition = money_condition
self.money_return = money_return def accept_cash(self,money):
if money>=self.money_condition:
return money - (money / self.money_condition) * self.money_return
return money #具体策略类
class Context(object): def __init__(self,csuper):
self.csuper = csuper def GetResult(self,money):
return self.csuper.accept_cash(money) if __name__ == '__main__':
money = input("原价: ")
strategy = {}
strategy[1] = Context(CashNormal())
strategy[2] = Context(CashRebate(0.8))
strategy[3] = Context(CashReturn(100,10))
mode = input("选择折扣方式: 1) 原价 2) 8折 3) 满100减10: ")
if mode in strategy:
csuper = strategy[mode]
else:
print "不存在的折扣方式"
csuper = strategy[1]
print "需要支付: ",csuper.GetResult(money)

这几个类的设计如下图:

使用一个策略类CashSuper定义需要的算法的公共接口,定义三个具体策略类:CashNormal,CashRebate,CashReturn,继承于CashSuper,定义一个上下文管理类,接收一个策略,并根据该策略得出结论,当需要更改策略时,只需要在实例的时候传入不同的策略就可以,免去了修改类的麻烦

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

最新文章

  1. SharpPcap网络包捕获框架的使用--实例代码在vs2005调试通过
  2. C#Abstract抽象类的语法
  3. 使用IO流实现一个简单的小Dome
  4. JAVA中I/O流
  5. android开发学习---layout布局、显示单位和如何进行单元测试
  6. 京东2017 C++一面
  7. Java中方法的重载
  8. 动态上传多个文件(asp)
  9. 自动化工具word文档批量转html
  10. 2-16 HDO1106
  11. Linux内核升级
  12. ExcelReport源码解析
  13. 让xcode8支持7.0的设备
  14. 解决xshell评估期已过的问题
  15. Java第5次实验提纲(集合)
  16. Python的安装及小程序练习
  17. Threading.Timer用法
  18. 2018.11.06 bzoj1093: [ZJOI2007]最大半连通子图(缩点+拓扑排序)
  19. 三:理解Page类的运行机制(例:在render方法中生成静态文件)
  20. SDL检查

热门文章

  1. SetApartmentState(ApartmentState state).Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process
  2. 嵌入式Linux+NetCore 笔记一
  3. NET 已知excel表格前面26个是a到z,27是aa28是ab,以此类推,N是多少
  4. java进销存管理系统的设计与实现-springboot源码
  5. Linux帮助——获取帮助
  6. Python基础22
  7. 深入浅出JVM的锁优化案例
  8. filebeat + ELK 部署篇
  9. linux源代码获取
  10. python_机器学习_监督学习模型_决策树