策略模式(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)
看以看到策略模式和工廠模式很像。但其實兩個的差別很微妙,工廠模式是直接創建具體的對象並用該對象去執行相應的動作。簡單工廠模式側重於生成對象。
而策略模式將這個操作給了Context類,沒有創建具體的對象,實現的代碼的進一步封裝,客戶端代碼並不需要知道具體的實現過程。 策略模式中注重具體算法的實現。
一個創建型模式,一個行為行模式。
