#与简单工厂模式相比,只将CashText暴露给了display.py。 import abc class CashSuper(metaclass=abc.ABCMeta): @abc.abstractmethod def accept_cash(self, money): pass
from cash_super import CashSuper class CashNormal(CashSuper): def __init__(self, *args): pass def accept_cash(self, money): return money
from cash_super import CashSuper class CashRebate(CashSuper): def __init__(self, *args): self.__money_rebate = args[0] def accept_cash(self, money): return money * self.__money_rebate
from cash_super import CashSuper class CashReturn(CashSuper): def __init__(self, *args): self.__money_condition = args[0] self.__money_return = args[1] def accept_cash(self, money): if money < self.__money_condition: return money return money - (money // self.__money_condition) * self.__money_return
from cash_normal import CashNormal from cash_rebate import CashRebate from cash_return import CashReturn class CashContext(object): factories = {'normal': CashNormal, 'rebate': CashRebate, 'return': CashReturn} def __init__(self, *args): args = args + (None,) * (3 - len(args)) self.__strategy = self.init_strategy(args[0])(args[1], args[2]) def init_strategy(self, strategy_type): if strategy_type not in CashContext.factories: raise Exception('策略未实现') return CashContext.factories.get(strategy_type) def get_result(self, money): return self.__strategy.accept_cash(money)
from cash_context import CashContext contest = CashContext('normal',20,4) print(contest.get_result(28))