1. 公共接口:
class MDCash:
def acceptCash(self):
return
2. 根据上面定义的接口实现:
# 正常
class MDCashNormal(MDCash):
def acceptCash(self, params):
return params
# 返5
class MDCaseReturn(MDCash):
def acceptCash(self, params):
return params - 5
# 打9折
class MDCashRobate(MDCash):
def acceptCash(self, params):
return params - params * 0.1
3. 实现context,封装不同行为的接口。
class MDCashContext:
def __init__(self, cashStrategy):
self.cashStrategy = cashStrategy
def performPay(self, params):
print self.cashStrategy.acceptCash(params)
4. 使用
if __name__ == '__main__':
context = MDCashContext(cashStrategy=MDCaseReturn())
context.performPay(100)
context = MDCashContext(cashStrategy=MDCashNormal())
context.performPay(100)
context = MDCashContext(cashStrategy=MDCashRobate())
context.performPay(100)
5. 所有代码:
#encoding:utf-8
class MDCash:
def acceptCash(self):
return
class MDCashNormal(MDCash):
def acceptCash(self, params):
return params
class MDCaseReturn(MDCash):
def acceptCash(self, params):
return params - 5
class MDCashRobate(MDCash):
def acceptCash(self, params):
return params - params * 0.1
class MDCashContext:
def __init__(self, cashStrategy):
self.cashStrategy = cashStrategy
def performPay(self, params):
print self.cashStrategy.acceptCash(params)
if __name__ == '__main__':
context = MDCashContext(cashStrategy=MDCaseReturn())
context.performPay(100)
context = MDCashContext(cashStrategy=MDCashNormal())
context.performPay(100)
context = MDCashContext(cashStrategy=MDCashRobate())
context.performPay(100)
运行结果:
95
100
90.0