1. 公共接口:python
class MDCash: def acceptCash(self): return
2. 根據上面定義的接口實現:code
# 正常 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,封裝不一樣行爲的接口。orm
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. 全部代碼:utf-8
#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)
運行結果:it
95 100 90.0