设计模式-策略模式 python

class CashSuper:
    def AcceptCash(self,money):
        return 0

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

class CashRebate(CashSuper):
    discount = 0
    def __init__(self,ds):
        self.discount = ds
    def AcceptCash(self,money):
        return money * self.discount

class CashReturn(CashSuper):
    total = 0;
    ret = 0;
    def __init__(self,t,r):
        self.total = t
        self.ret = r
    def AcceptCash(self,money):
        if (money>=self.total):
            return money - self.ret
        else:
            return money


class CashContext:
    strategy = {}
    strategy[1] = CashNormal()
    strategy[2] = CashRebate(0.8)
    strategy[3] = CashReturn(300,100)
    # def __init__(self,i):
    #     self.cs = strategy[i]
    # def GetResult(self,money):
    #     return self.cs.AcceptCash(money)

    def createCashSuper(self,ch,money):
        if ch in self.strategy:
            op = self.strategy[ch]
        else:
            op = strategy[1]

        return op.AcceptCash(money)

if __name__ == "__main__":
    money = input("money:")
    abc = CashContext()
    ctype = input("type:[1]for normal,[2]for 80% discount [3]for 300 -100.")



    # if ctype in abc.strategy:
    #     cc = CashContext.strategy[ctype]
    # else:
    #     print "Undefine type.Use normal mode."
    #     cc = CashContext.strategy[1]

    print "you will pay:%d" %(abc.createCashSuper(ctype,money))




# class CashContext:
#     def __init__(self,csuper):
#         self.cs = csuper
#     def GetResult(self,money):
#         return self.cs.AcceptCash(money)
#
# if __name__ == "__main__":
#     money = input("money:")
#     strategy = {}
#     strategy[1] = CashContext(CashNormal())
#     strategy[2] = CashContext(CashRebate(0.8))
#     strategy[3] = CashContext(CashReturn(300,100))
#     ctype = input("type:[1]for normal,[2]for 80% 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.GetResult(money))

  

转载于:https://www.cnblogs.com/zinedine/p/4438196.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值