12-Python與設計模式--策略模式
一、客戶訊息通知
假設某司維護著一些客戶資料,需要在該司有新產品上市或者舉行新活動時通知客戶。現通知客戶的方式有兩種:簡訊通知、郵件通知。應如何設計該系統的客戶通知部分?為解決該問題,我們先構造客戶類,包括客戶常用的聯絡方式和基本資訊,同時也包括要傳送的內容。
class customer: customer_name="" snd_way="" info="" phone="" email="" def setPhone(self,phone): self.phone=phone def setEmail(self,mail): self.email=mail def getPhone(self): return self.phone def getEmail(self): return self.email def setInfo(self,info): self.info=info def setName(self,name): self.customer_name=name def setBrdWay(self,snd_way): self.snd_way=snd_way def sndMsg(self): self.snd_way.send(self.info)
snd_way向客戶傳送資訊的方式,該方式置為可設,即可根據業務來進行策略的選擇。
傳送方式構建如下:
class msgSender: dst_code="" def setCode(self,code): self.dst_code=code def send(self,info): pass class emailSender(msgSender): def send(self,info): print "EMAIL_ADDRESS:%s EMAIL:%s"%(self.dst_code,info) class textSender(msgSender): def send(self,info): print "TEXT_CODE:%s EMAIL:%s"%(self.dst_code,info)
在業務場景中將傳送方式作為策略,根據需求進行傳送。
if __name__=="__main__": customer_x=customer() customer_x.setName("CUSTOMER_X") customer_x.setPhone("10023456789") customer_x.setEmail("[email protected]") customer_x.setInfo("Welcome to our new party!") text_sender=textSender() text_sender.setCode(customer_x.getPhone()) customer_x.setBrdWay(text_sender) customer_x.sndMsg() mail_sender=emailSender() mail_sender.setCode(customer_x.getEmail()) customer_x.setBrdWay(mail_sender) customer_x.sndMsg()
結果列印如下:
PHONE_NUMBER:10023456789 TEXT:Welcome to our new party!
EMAIL_ADDRESS:[email protected] EMAIL:Welcome to our new party!
二、策略模式
策略模式定義如下:定義一組演算法,將每個演算法都封裝起來,並使他們之間可互換。以上述例子為例,customer類扮演的角色(Context)直接依賴抽象策略的介面,在具體策略實現類中即可定義個性化的策略方式,且可以方便替換。
上一節中我們介紹了橋接模式,仔細比較一下橋接模式和策略模式,如果把策略模式的Context設計成抽象類和實現類的方式,那麼策略模式和橋接模式就可以劃等號了。從類圖看上去,橋接模式比策略模式多了對一種角色(抽象角色)的抽象。二者結構的高度同構,也只能讓我們從使用意圖上去區分兩種模式:橋接模式解決抽象角色和實現角色都可以擴充套件的問題;而策略模式解決演算法切換和擴充套件的問題。
三、策略模式的優點和應用場景
優點:
1、各個策略可以自由切換:這也是依賴抽象類設計介面的好處之一;
2、減少程式碼冗餘;
3、擴充套件性優秀,移植方便,使用靈活。
應用場景:
1、演算法策略比較經常地需要被替換時,可以使用策略模式。如現在超市前臺,會常遇到刷卡、某寶支付、某信支付等方式,就可以參考策略模式。
四、策略模式的缺點
1、專案比較龐大時,策略可能比較多,不便於維護;
2、策略的使用方必須知道有哪些策略,才能決定使用哪一個策略,這與迪米特法則是相違背的。