99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python設計模式之策略模式
Python設計模式之策略模式
2018-04-23
收藏

Python設計模式之策略模式

設計模式是我們實際應用開發(fā)中必不可缺的,對設計模式的理解有助于我們寫出可讀性和擴展更高的應用程序。雖然設計模式與語言無關,但并不意味著每一個模式都能在任何語言中使用,所以有必要去針對語言的特性去做了解。設計模式特別是對于java語言而言,已經(jīng)有過非常多的大牛寫過,所以這里我就不重復了。對于Python來說就相對要少很多,特別是python語言具有很多高級的特性,而不需要了解這些照樣能滿足開發(fā)中的很多需求,所以很多人往往忽視了這些,這里我們來在Pythonic中來感受一下設計模式。

1.介紹

策略模式也是常見的設計模式之一,它是指對一系列的算法定義,并將每一個算法封裝起來,而且使它們還可以相互替換。策略模式讓算法獨立于使用它的客戶而獨立變化。
這是比較官方的說法,看著明顯的一股比較抽象的感覺,通俗來講就是針對一個問題而定義出一個解決的模板,這個模板就是具體的策略,每個策略都是按照這個模板來的。這種情況下我們有新的策略時就可以直接按照模板來寫,而不會影響之前已經(jīng)定義好的策略。

2.具體實例

這里我用的《流暢的Python》中的實例,剛好雙11過去不久,相信許多小伙伴也是掏空了腰包,哈哈。那這里就以電商領域的根據(jù)客戶的屬性或訂單中的商品數(shù)量來計算折扣的方式來進行講解,首先來看看下面這張圖。

通過這張圖,相信能對策略模式的流程有個比較清晰的了解了。然后看看具體的實現(xiàn)過程,首先我們用namedtuple來定義一個Customer,雖然這里是說設計模式,考慮到有些小伙伴可能對Python中的具名元組不太熟悉,所以這里也簡單的說下。
namedtuple用來構建一個帶字段名的元組和一個有名字的類,這樣說可能還是有些抽象,這里來看看下面的代碼

from collections import namedtuple
City = namedtuple('City','name country provinces')
這里測試就直接如下
changsha = City('Changsha','China','Hunan')
print(changsha)

結果如下
City(name='Changsha', country='China', province='Hunan')
還可以直接調用字段
print(changsha.name)
更多用法可以去看看官方文檔,這里重點還是講設計模式。
好了,先來看看用類實現(xiàn)的策略模式

# 策略設計模式實例

from abc import ABC, abstractmethod
from collections import namedtuple

# 創(chuàng)建一個具名元組
Customer = namedtuple('Customer', 'name fidelity')


class LineItem:

    def __init__(self, product, quantity, price):
        self.product = product
        self.quantity = quantity
        self.price = price

    def total(self):
        return self.price * self.quantity


# 上下文
class Order:
  
 ?。?傳入三個參數(shù),分別是消費者,購物清單,促銷方式
    def __init__(self, customer, cart, promotion=None):
        self.customer = customer
        self.cart = list(cart)
        self.promotion = promotion

    def total(self):
        if not hasattr(self, '__total'):
            self.__total = sum(item.total() for item in self.cart)
        return self.__total

    def due(self):
        if self.promotion is None:
            discount = 0
        else:
            discount = self.promotion.discount(self)
        return self.total() - discount

    # 輸出具體信息
    def __repr__(self):
        fmt = '<Order total: {:.2f} due: {:.2f}>'
        return fmt.format(self.total(), self.due())


# 策略 抽象基類
class Promotion(ABC):

    @abstractmethod
    def discount(self, order):
        """
        :param order:
        :return: 返回折扣金額(正值)
        """


# 第一個具體策略
class FidelityPromo(Promotion):
    """ 為積分為1000或以上的顧客提供5%的折扣 """

    def discount(self, order):
        return order.total() * .05 if order.customer.fidelity >= 1000 else 0


# 第二個具體策略
class BulkItemPromo(Promotion):
    """ 單個商品為20個或以上時提供10%折扣"""

    def discount(self, order):
        discount = 0
        for item in order.cart:
            if item.quantity >= 20:
                discount = item.total() * .1
        return discount


# 第三個具體策略
class LargeOrderPromo(Promotion):
    """ 訂單中的不同商品達到10個或以上時提供%7的折扣"""

    def discount(self, order):
        distinct_items = {item.product for item in order.cart}
        if len(distinct_items) >= 10:
            return order.total() * .07
        return 0

這里是用類對象來實現(xiàn)的策略模式,每個具體策略類(折扣方式)都繼承了Promotion這個基類,因為discount()是一個抽象函數(shù),所以繼承Promotion的子類都需要重寫discount()函數(shù)(也就是進行具體的打折信息的函數(shù)),這樣一來,就很好的實現(xiàn)對象之間的解耦。這里的折扣方式有兩類,一類是根據(jù)用戶的積分,一類是根據(jù)用戶所購買商品的數(shù)量。具體的折扣信息也都在代碼塊里面注釋了,這里就不重復了,接下來我們來看看具體的測試用例

joe = Customer('John Doe', 0)
ann = Customer('Ann Smith', 1100)
cart = [LineItem('banana', 4, .5),
        LineItem('apple', 10, 1.5),
        LineItem('watermellon', 5, 5.0)]
print('John: ', Order(joe, cart, FidelityPromo()))
print('Ann: ', Order(ann, cart, FidelityPromo()))
這里定義了兩消費者,John初始積分為0,Ann初始積分為1100,然后商品購買了4個香蕉,10個蘋果,5個西瓜...說的都要流口水了,哈哈哈。回到正題,輸出時采用第一種折扣方式,Run一下

John:  <Order total: 42.00 due: 42.00>
Ann:  <Order total: 42.00 due: 39.90>
3.優(yōu)化措施
?類變函數(shù)

上面的策略模式是使用的類對象實現(xiàn)的,其實我們還可以用函數(shù)對象的方法實現(xiàn),看看具體的代碼

# 策略設計模式實例

from collections import namedtuple

# 創(chuàng)建一個具名元組
Customer = namedtuple('Customer', 'name fidelity')


class LineItem:

    def __init__(self, product, quantity, price):
        self.product = product
        self.quantity = quantity
        self.price = price

    def total(self):
        return self.price * self.quantity


# 上下文
class Order:

    def __init__(self, customer, cart, promotion=None):
        self.customer = customer
        self.cart = list(cart)
        self.promotion = promotion

    def total(self):
        if not hasattr(self, '__total'):
            self.__total = sum(item.total() for item in self.cart)
        return self.__total

    def due(self):
        if self.promotion is None:
            discount = 0
        else:
            discount = self.promotion.discount(self)
        return self.total() - discount

    def __repr__(self):
        fmt = '<Order total: {:.2f} due: {:.2f}>'
        return fmt.format(self.total(), self.due())


# 第一個具體策略
def fidelity_promo(order):
    """ 為積分為1000或以上的顧客提供5%的折扣 """

    return order.total() * .05 if order.customer.fidelity >= 1000 else 0


# 第二個具體策略
def bulk_item_promo(order):
    """ 單個商品為20個或以上時提供10%折扣"""

    discount = 0
    for item in order.cart:
        if item.quantity >= 20:
            discount = item.total() * .1
    return discount


# 第三個具體策略
def large_order_promo(order):
    """ 訂單中的不同商品達到10個或以上時提供%7的折扣"""

    distinct_items = {item.product for item in order.cart}
    if len(distinct_items) >= 10:
        return order.total() * .07
    return 0    
這種方式?jīng)]有了抽象類,并且每個策略都是函數(shù),實現(xiàn)同樣的功能,代碼量更加少,并且測試的時候可以直接把促銷函數(shù)作為參數(shù)傳入,這里就不多說了。
?選擇最佳策略

細心的朋友可能觀察到,我們這樣每次對商品進行打折處理時,都需要自己選擇折扣方式,這樣數(shù)量多了就會非常的麻煩,那么有沒有辦法讓系統(tǒng)幫我們自動選擇呢?當然是有的,這里我們可以定義一個數(shù)組,把折扣策略的函數(shù)當作元素傳進去。

promos = [fidelity_promo,bulk_item_promo,large_order_promo]

然后定義一個函數(shù)

def best_promo(order):
    """  選擇可用的最佳折扣 """

    return max(promo(order) for promo in promos)
這樣一來就省了很多時間,系統(tǒng)幫我們自動選擇。但是仍然有一個問題,這個數(shù)組的元素需要我們手動輸入,雖然工作量小,但是對于有強迫癥的猿來說,依然是不行的,能用自動化的方式就不要用手動,所以繼續(xù)做優(yōu)化。

promos = [globals()[name] for name in globals()
              if name.endswith('_promo')
              and name != 'best_promo']

這里使用了globals()函數(shù),我們就是使用這個函數(shù)來進行全局查找以’_promo’結尾的函數(shù),并且過濾掉best_promo函數(shù),又一次完成了我們的自動化優(yōu)化。
最后,這篇blog就到這里了,相信你我都更加了解Python中的策略模式了,這里我推薦對Python感興趣的朋友去看一下《Fluent Python》這本書,里面講述了很多的高級特性, 更加讓我們體驗到Python中的美學。



數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師考試動態(tài)
數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調,回調的第一個參數(shù)驗證碼對象,之后可以使用它調用相應的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }