最近正在持续更新源码库,代码都是参考大话设计模式翻成python版,完整代码片段请到github上去下载.
https://github.com/zhengtong0898/python-patterns
参考:
书籍<<大话设计模式>> 第二章 2.5 -- 2.6 小节
Python 3.x
# -.- coding:utf-8 -.-# __author__ = 'zhengtong'# 知识点:面向对象的编程,并不是类越多越好,类的划分是为了封装,# 但分类的基础是抽象,具有相同属性和功能的对象的抽象集合才是类。_price_repr = '单价:'_number_repr = '数量:'_total_repr = '合计:'class Strategy: """ 策略和简单工厂的结合 这里将原来的CashFactory工厂中的代码进行了整合. """ def __init__(self, typed, **kwargs): if typed == 1: self.result = CashNormal(**kwargs) elif typed == 2: self.result = CashReturn(300, 100, **kwargs) elif typed == 3: self.result = CashRebate(0.8, **kwargs) else: raise KeyError('无效的返利选择') def get_result(self): return self.result.accept_cash()class CashSuper: """现金收取类(抽象类)""" def __init__(self, money): self.money = money def accept_cash(self): raise NotImplementedErrorclass CashNormal(CashSuper): """正常收费子类""" def accept_cash(self): return self.moneyclass CashRebate(CashSuper): """打折收费子类""" def __init__(self, rebate, **kwargs): """ 这里为什么采用**kwargs, 请参考下面这个链接: http://my.oschina.net/zhengtong0898/blog/670917 """ super(CashRebate, self).__init__(**kwargs) self.rebate = rebate def accept_cash(self): return self.money * self.rebateclass CashReturn(CashSuper): """返利收费子类""" def __init__(self, condition, money_return, **kwargs): super(CashReturn, self).__init__(**kwargs) self.condition = int(condition) self.money_return = int(money_return) def accept_cash(self): result = self.money # 当满足了返利条件, 则采用计算规则. if self.money >= self.condition: result = self.money - int(self.money / self.condition) * self.money_return return resultdef main(): result = 0 while True: try: prices = int(input(_price_repr)) number = int(input(_number_repr)) price_off = int(input('返利模式: 1(正常收费), 2(满300返100), 3(打8折):')) money = Strategy(price_off, money=prices*number).get_result() result += money print(_price_repr, prices, _number_repr, number, _total_repr, money) except KeyboardInterrupt: print('') print('oops: 检测到Ctrl + C组合键, 正在返回总费用并推出程序') break return resultif __name__ == '__main__': print('温馨提示:输入Ctrl + C组合键可得到总数和退出程序.') print(main())