策略模式(Strategy Pattern):它定義了算法家族,分別封裝起來,讓他們之間可以相互替換,此模式讓算法的變化,不會影響到使用算法的客戶.
下面是一個商場活動的實現
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 __author__ = 'Andy' 5 ''' 6 大話設計模式 7 設計模式——策略模式 8 策略模式(strategy):它定義了算法家族,分別封裝起來,讓他們之間可以相互替換,此模式讓算法的變化,不會影響到使用算法的客戶 9 ''' 10 11 #現金收費抽象類 12 class CashSuper(object): 13 14 def accept_cash(self,money): 15 pass 16 #正常收費子類 17 class CashNormal(CashSuper): 18 19 def accept_cash(self,money): 20 return money 21 22 #打折收費子類 23 class CashRebate(CashSuper): 24 25 def __init__(self,discount=1): 26 self.discount = discount 27 28 def accept_cash(self,money): 29 return money * self.discount 30 31 #返利收費子類 32 class CashReturn(CashSuper): 33 34 def __init__(self,money_condition=0,money_return=0): 35 self.money_condition = money_condition 36 self.money_return = money_return 37 38 def accept_cash(self,money): 39 if money>=self.money_condition: 40 return money - (money / self.money_condition) * self.money_return 41 return money 42 43 #具體策略類 44 class Context(object): 45 46 def __init__(self,csuper): 47 self.csuper = csuper 48 49 def GetResult(self,money): 50 return self.csuper.accept_cash(money) 51 52 53 54 55 if __name__ == '__main__': 56 money = input("原價: ") 57 strategy = {} 58 strategy[1] = Context(CashNormal()) 59 strategy[2] = Context(CashRebate(0.8)) 60 strategy[3] = Context(CashReturn(100,10)) 61 mode = input("選擇折扣方式: 1) 原價 2) 8折 3) 滿100減10: ") 62 if mode in strategy: 63 csuper = strategy[mode] 64 else: 65 print "不存在的折扣方式" 66 csuper = strategy[1] 67 print "需要支付: ",csuper.GetResult(money)
這幾個類的設計如下圖:
使用一個策略類CashSuper定義需要的算法的公共接口,定義三個具體策略類:CashNormal,CashRebate,CashReturn,繼承於CashSuper,定義一個上下文管理類,接收一個策略,並根據該策略得出結論,當需要更改策略時,只需要在實例的時候傳入不同的策略就可以,免去了修改類的麻煩
作者:Andy
出處:http://www.cnblogs.com/onepiece-andy/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。