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、策略的使用方必須知道有哪些策略,才能決定使用哪一個策略,這與迪米特法則是相違背的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章