python实现策略模式

#与简单工厂模式相比,只将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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值