python设计模式(一)--简单工厂(中)

最近正在持续更新源码库,代码都是参考大话设计模式翻成python版,完整代码片段请到github上去下载.

https://github.com/zhengtong0898/python-patterns

 

参考:

    书籍<<大话设计模式>> 第二章 2.1 -- 2.3

 

Python 3.x

# -.- coding:utf-8 -.-
# __author__ = 'zhengtong'
# 知识点:面向对象的编程,并不是类越多越好,类的划分是为了封装,
#         但分类的基础是抽象,具有相同属性和功能的对象的抽象集合才是类。

_price_repr = '单价:'
_number_repr = '数量:'
_total_repr = '合计:'


class CashSuper:
    """现金收取类(抽象类)"""

    def __init__(self, money):
        self.money = money

    def accept_cash(self):
        raise NotImplementedError


class CashNormal(CashSuper):
    """正常收费子类"""

    def accept_cash(self):
        return self.money


class 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.rebate


class 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 result


class CashFactory:
    """现金收费工厂类"""

    @staticmethod
    def create_cash_accept(typed, **kwargs):
        if typed == 1:
            result = CashNormal(**kwargs).accept_cash()
        elif typed == 2:
            result = CashReturn(300, 100, **kwargs).accept_cash()
        elif typed == 3:
            result = CashRebate(0.8, **kwargs).accept_cash()
        else:
            raise KeyError('无效的返利选择')
        return result


def 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 = CashFactory.create_cash_accept(price_off, money=prices*number)
            result += money
            print(_price_repr, prices, _number_repr, number, _total_repr, money)
        except KeyboardInterrupt:
            print('')
            print('oops: 检测到Ctrl + C组合键, 正在返回总费用并推出程序')
            break
    return result


if __name__ == '__main__':
    print('温馨提示:输入Ctrl + C组合键可得到总数和退出程序.')
    print(main())

 

你可能感兴趣的:(python设计模式(一)--简单工厂(中))