色综合图-色综合图片-色综合图片二区150p-色综合图区-玖玖国产精品视频-玖玖香蕉视频

您的位置:首頁技術(shù)文章
文章詳情頁

詳解Python設(shè)計(jì)模式之策略模式

瀏覽:76日期:2022-07-21 10:46:38

雖然設(shè)計(jì)模式與語言無關(guān),但這并不意味著每一個(gè)模式都能在每一門語言中使用。《設(shè)計(jì)模式:可復(fù)用面向?qū)ο筌浖幕A(chǔ)》一書中有 23 個(gè)模式,其中有 16 個(gè)在動(dòng)態(tài)語言中“不見了,或者簡化了”。

1、策略模式概述

策略模式:定義一系列算法,把它們一一封裝起來,并且使它們之間可以相互替換。此模式讓算法的變化不會(huì)影響到使用算法的客戶。

電商領(lǐng)域有個(gè)使用“策略”模式的經(jīng)典案例,即根據(jù)客戶的屬性或訂單中的商品計(jì)算折扣。

假如一個(gè)網(wǎng)店制定了下述折扣規(guī)則。

有 1000 或以上積分的顧客,每個(gè)訂單享 5% 折扣。 同一訂單中,單個(gè)商品的數(shù)量達(dá)到 20 個(gè)或以上,享 10% 折扣。 訂單中的不同商品達(dá)到 10 個(gè)或以上,享 7% 折扣。

簡單起見,我們假定一個(gè)訂單一次只能享用一個(gè)折扣。

UML類圖如下:

詳解Python設(shè)計(jì)模式之策略模式

Promotion 抽象類提供了不同算法的公共接口,fidelityPromo、BulkPromo 和 LargeOrderPromo 三個(gè)子類實(shí)現(xiàn)具體的“策略”,具體策略由上下文類的客戶選擇。

在這個(gè)示例中,實(shí)例化訂單(Order 類)之前,系統(tǒng)會(huì)以某種方式選擇一種促銷折扣策略,然后把它傳給 Order 構(gòu)造方法。具體怎么選擇策略,不在這個(gè)模式的職責(zé)范圍內(nèi)。(選擇策略可以使用工廠模式。)

2、傳統(tǒng)方法實(shí)現(xiàn)策略模式:

from abc import ABC, abstractmethodfrom collections import namedtupleCustomer = namedtuple(’Customer’, ’name fidelity’)class LineItem: '''訂單中單個(gè)商品的數(shù)量和單價(jià)''' def __init__(self, product, quantity, price): self.product = product self.quantity = quantity self.price = price def total(self): return self.price * self.quantityclass 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 = ’<訂單 總價(jià): {:.2f} 實(shí)付: {:.2f}>’ return fmt.format(self.total(), self.due())class Promotion(ABC): # 策略:抽象基類 @abstractmethod def discount(self, order): '''返回折扣金額(正值)'''class FidelityPromo(Promotion): # 第一個(gè)具體策略 '''為積分為1000或以上的顧客提供5%折扣''' def discount(self, order): return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0class BulkItemPromo(Promotion): # 第二個(gè)具體策略 '''單個(gè)商品為20個(gè)或以上時(shí)提供10%折扣''' def discount(self, order): discount = 0 for item in order.cart: if item.quantity >= 20: discount += item.total() * 0.1 return discountclass LargeOrderPromo(Promotion): # 第三個(gè)具體策略 '''訂單中的不同商品達(dá)到10個(gè)或以上時(shí)提供7%折扣''' def discount(self, order): distinct_items = {item.product for item in order.cart} if len(distinct_items) >= 10: return order.total() * 0.07 return 0joe = Customer(’John Doe’, 0)ann = Customer(’Ann Smith’, 1100)cart = [LineItem(’banana’, 4, 0.5), LineItem(’apple’, 10, 1.5), LineItem(’watermellon’, 5, 5.0)]print(’策略一:為積分為1000或以上的顧客提供5%折扣’)print(Order(joe, cart, FidelityPromo()))print(Order(ann, cart, FidelityPromo()))banana_cart = [LineItem(’banana’, 30, 0.5), LineItem(’apple’, 10, 1.5)]print(’策略二:單個(gè)商品為20個(gè)或以上時(shí)提供10%折扣’)print(Order(joe, banana_cart, BulkItemPromo()))long_order = [LineItem(str(item_code), 1, 1.0) for item_code in range(10)]print(’策略三:訂單中的不同商品達(dá)到10個(gè)或以上時(shí)提供7%折扣’)print(Order(joe, long_order, LargeOrderPromo()))print(Order(joe, cart, LargeOrderPromo()))

輸出:

策略一:為積分為1000或以上的顧客提供5%折扣<訂單 總價(jià): 42.00 實(shí)付: 42.00><訂單 總價(jià): 42.00 實(shí)付: 39.90>策略二:單個(gè)商品為20個(gè)或以上時(shí)提供10%折扣<訂單 總價(jià): 30.00 實(shí)付: 28.50>策略三:訂單中的不同商品達(dá)到10個(gè)或以上時(shí)提供7%折扣<訂單 總價(jià): 10.00 實(shí)付: 9.30><訂單 總價(jià): 42.00 實(shí)付: 42.00>

3、使用函數(shù)實(shí)現(xiàn)策略模式

在傳統(tǒng)策略模式中,每個(gè)具體策略都是一個(gè)類,而且都只定義了一個(gè)方法,除此之外沒有其他任何實(shí)例屬性。它們看起來像是普通的函數(shù)一樣。的確如此,在 Python 中,我們可以把具體策略換成了簡單的函數(shù),并且去掉策略的抽象類。

from collections import namedtupleCustomer = 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.quantityclass 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(self) return self.total() - discount def __repr__(self): fmt = ’<訂單 總價(jià): {:.2f} 實(shí)付: {:.2f}>’ return fmt.format(self.total(), self.due())def fidelity_promo(order): '''為積分為1000或以上的顧客提供5%折扣''' return order.total() * .05 if order.customer.fidelity >= 1000 else 0def bulk_item_promo(order): '''單個(gè)商品為20個(gè)或以上時(shí)提供10%折扣''' discount = 0 for item in order.cart: if item.quantity >= 20: discount += item.total() * .1 return discountdef large_order_promo(order): '''訂單中的不同商品達(dá)到10個(gè)或以上時(shí)提供7%折扣''' distinct_items = {item.product for item in order.cart} if len(distinct_items) >= 10: return order.total() * .07 return 0joe = Customer(’John Doe’, 0)ann = Customer(’Ann Smith’, 1100)cart = [LineItem(’banana’, 4, 0.5), LineItem(’apple’, 10, 1.5), LineItem(’watermellon’, 5, 5.0)]print(’策略一:為積分為1000或以上的顧客提供5%折扣’)print(Order(joe, cart, fidelity_promo))print(Order(ann, cart, fidelity_promo))banana_cart = [LineItem(’banana’, 30, 0.5), LineItem(’apple’, 10, 1.5)]print(’策略二:單個(gè)商品為20個(gè)或以上時(shí)提供10%折扣’)print(Order(joe, banana_cart, bulk_item_promo))long_order = [LineItem(str(item_code), 1, 1.0) for item_code in range(10)]print(’策略三:訂單中的不同商品達(dá)到10個(gè)或以上時(shí)提供7%折扣’)print(Order(joe, long_order, large_order_promo))print(Order(joe, cart, large_order_promo))

其實(shí)只要是支持高階函數(shù)的語言,就可以如此實(shí)現(xiàn),例如 C# 中,可以用委托實(shí)現(xiàn)。只是如此實(shí)現(xiàn)反而使代碼變得復(fù)雜不易懂。而 Python 中,函數(shù)天然就可以當(dāng)做參數(shù)來傳遞。

值得注意的是,《設(shè)計(jì)模式:可復(fù)用面向?qū)ο筌浖幕A(chǔ)》一書的作者指出:“策略對象通常是很好的享元。” 享元是可共享的對象,可以同時(shí)在多個(gè)上下文中使用。共享是推薦的做法,這樣不必在每個(gè)新的上下文(這里是 Order 實(shí)例)中使用相同的策略時(shí)不斷新建具體策略對象,從而減少消耗。因此,為了避免 [策略模式] 的運(yùn)行時(shí)消耗,可以配合 [享元模式] 一起使用,但這樣,代碼行數(shù)和維護(hù)成本會(huì)不斷攀升。

在復(fù)雜的情況下,需要具體策略維護(hù)內(nèi)部狀態(tài)時(shí),可能需要把“策略”和“享元”模式結(jié)合起來。但是,具體策略一般沒有內(nèi)部狀態(tài),只是處理上下文中的數(shù)據(jù)。此時(shí),一定要使用普通的函數(shù),別去編寫只有一個(gè)方法的類,再去實(shí)現(xiàn)另一個(gè)類聲明的單函數(shù)接口。函數(shù)比用戶定義的類的實(shí)例輕量,而且無需使用“享元”模式,因?yàn)楦鱾€(gè)策略函數(shù)在 Python 編譯模塊時(shí)只會(huì)創(chuàng)建一次。普通的函數(shù)也是“可共享的對象,可以同時(shí)在多個(gè)上下文中使用”。

以上就是詳解Python設(shè)計(jì)模式之策略模式的詳細(xì)內(nèi)容,更多關(guān)于Python 策略模式的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 国产成人在线视频 | 国产在线观看一区精品 | 国产精品自拍亚洲 | 欧美成人性色生活片免费在线观看 | 免费观看欧美精品成人毛片 | 午夜伦4480yy妇女久久久 | 日本在线看小视频网址 | 韩国美女爽快毛片免费 | 爽爽爽爽爽爽爽成人免费观看 | 亚洲成人国产精品 | 免费播放欧美毛片 | 国产成人亚洲精品老王 | 国产女厕所 | 2018久久久国产精品 | 亚洲在线免费视频 | 精品国产欧美另类一区 | 初爱视频教程在线观看高清 | 国产精品视频永久免费播放 | 国产精品久久久久久久久免费 | 国产精品二区三区 | 久久久久久免费一区二区三区 | 草草影院ccyy国产日本欧美 | 国产精品高清在线观看地址 | 亚洲加勒比久久88色综合1 | 成年人在线免费网站 | 女黄人东京手机福利视频 | 国产杨幂福利在线视频观看 | 免费看美女无遮掩的软件 | 中文字幕免费在线视频 | 国产福利久久 | 久久久久免费视频 | 亚洲国产欧美日韩第一香蕉 | 国产日韩欧美久久久 | 九九色网站 | 人与禽的免费一级毛片 | 视频一区色眯眯视频在线 | 美女黄视频在线观看 | 成人做爰在线视频 | 国产一区二区三区亚洲欧美 | 欧美三级不卡视频 | tom影院亚洲国产日本一区 |