本文實例講述了Python設計模式之策略模式。分享給大家供大家參考,具體如下:
策略模式(Strategy Pattern):它定義了算法家族,分別封裝起來,讓他們之間可以相互替換,此模式讓算法的變化,不會影響到使用算法的客戶.
下面是一個商場活動的實現
#!/usr/bin/env python# -*- coding:utf-8 -*-__author__ = 'Andy''''大話設計模式設計模式——策略模式策略模式(strategy):它定義了算法家族,分別封裝起來,讓他們之間可以相互替換,此模式讓算法的變化,不會影響到使用算法的客戶'''#現金收費抽象類class CashSuper(object): def accept_cash(self,money): pass#正常收費子類class CashNormal(CashSuper): def accept_cash(self,money): return money#打折收費子類class CashRebate(CashSuper): def __init__(self,discount=1): self.discount = discount def accept_cash(self,money): return money * self.discount#返利收費子類class CashReturn(CashSuper): def __init__(self,money_condition=0,money_return=0): self.money_condition = money_condition self.money_return = money_return def accept_cash(self,money): if money>=self.money_condition: return money - (money / self.money_condition) * self.money_return return money#具體策略類class Context(object): def __init__(self,csuper): self.csuper = csuper def GetResult(self,money): return self.csuper.accept_cash(money)if __name__ == '__main__': money = input("原價: ") strategy = {} strategy[1] = Context(CashNormal()) strategy[2] = Context(CashRebate(0.8)) strategy[3] = Context(CashReturn(100,10)) mode = input("選擇折扣方式: 1) 原價 2) 8折 3) 滿100減10: ") if mode in strategy: csuper = strategy[mode] else: print "不存在的折扣方式" csuper = strategy[1] print "需要支付: ",csuper.GetResult(money)運行結果:
原價: 500
選擇折扣方式: 1) 原價 2) 8折 3) 滿100減10: 2
需要支付: 400.0
這幾個類的設計如下圖:

使用一個策略類CashSuper定義需要的算法的公共接口,定義三個具體策略類:CashNormal,CashRebate,CashReturn,繼承于CashSuper,定義一個上下文管理類,接收一個策略,并根據該策略得出結論,當需要更改策略時,只需要在實例的時候傳入不同的策略就可以,免去了修改類的麻煩
更多關于Python相關內容可查看本站專題:《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答