(Python3 代码实现)《大话设计模式》二:策略模式

在这里插入图片描述

  • 模式特点:定义算法家族并且分别封装,它们之间可以相互替换而不影响客户端。
  • 程序实例:商场收银软件,需要根据不同的销售策略方式进行收费
  • 代码特点:不同于同例1,这里使用字典是为了避免关键字不在字典导致bug的陷阱。
class CashSuper:
    def accept_cash(self, money):
        pass


class CashNormal(CashSuper):
    def accept_cash(self, money):
        return money


class CashRebate(CashSuper):
    def __init__(self, r):
        self.rebate = r

    def accept_cash(self, money):
        return money * self.rebate


class CashReturn(CashSuper):
    def __init__(self, t, r):
        self.total = t
        self.ret = r

    def accept_cash(self, money):
        if money >= self.total:
            return money - self.ret
        else:
            return money


class CashContext:
    def __init__(self, csuper):
        self.cs = csuper

    def get_result(self, money):
        return self.cs.accept_cash(money)


if __name__ == '__main__':
    money = int(input("money: "))
    strategy = {}
    strategy[1] = CashContext(CashNormal())
    strategy[2] = CashContext(CashRebate(0.5))
    strategy[3] = CashContext(CashReturn(300, 100))

    ctype  = int(input("type:[1] for normal, [2]for 50% discount, [3]for 300-100: "))

    if ctype in strategy:
        cc = strategy[ctype]
    else:
        print("Undefine type.Use normal mode.")
        cc = strategy[1]

    print("you will pay: %d" % cc.get_result(money))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值