策略模式用于多选择,但同时又要考虑其他因素:
class Cash():
def register(self,money):
return money
class UnionPay():
def __init__(self,discount):
self.discount = discount
def register(self,money):
return money*self.discount
class Alipay():
def __init__(self,full,reduction):
self.full = full
self.reduction = reduction
def register(self,money):
return money-money//self.full*self.reduction
class Cashier():
def __init__(self,strategy):
self.strategy = strategy
def result(self,money):
return self.strategy.register(money)
a ={}
a[0] = Cashier(Cash())
a[1] = Cashier(UnionPay(0.95))
a[2] = Cashier(Alipay(300,30))
strategy = int(input("请输入支付策略:"))
money = float(input("请输入商品金额:"))
if strategy in a.keys():
pay = a[strategy].result(money)
else:
pay = a[0].result(money)
print(pay)