欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Python設計模式之策略模式

 更新時間:2020年06月15日 16:05:57   作者:丹楓無跡  
這篇文章主要介紹了Python設計模式之策略模式的相關知識,文中講解非常詳細,代碼幫助大家更好的理解和學習,感興趣的朋友可以了解下

雖然設計模式與語言無關,但這并不意味著每一個模式都能在每一門語言中使用?!对O計模式:可復用面向對象軟件的基礎》一書中有 23 個模式,其中有 16 個在動態(tài)語言中“不見了,或者簡化了”。

1、策略模式概述

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

電商領域有個使用“策略”模式的經典案例,即根據客戶的屬性或訂單中的商品計算折扣。

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

  • 有 1000 或以上積分的顧客,每個訂單享 5% 折扣。
  • 同一訂單中,單個商品的數量達到 20 個或以上,享 10% 折扣。
  • 訂單中的不同商品達到 10 個或以上,享 7% 折扣。

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

UML類圖如下:

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

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

2、傳統(tǒng)方法實現策略模式:

from abc import ABC, abstractmethod
from collections import namedtuple

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 = '<訂單 總價: {:.2f} 實付: {:.2f}>'
 return fmt.format(self.total(), self.due())


class Promotion(ABC): # 策略:抽象基類
 @abstractmethod
 def discount(self, order):
 """返回折扣金額(正值)"""


class FidelityPromo(Promotion): # 第一個具體策略
 """為積分為1000或以上的顧客提供5%折扣"""
 def discount(self, order):
 return order.total() * 0.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() * 0.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() * 0.07
 return 0


joe = 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('策略二:單個商品為20個或以上時提供10%折扣')
print(Order(joe, banana_cart, BulkItemPromo()))

long_order = [LineItem(str(item_code), 1, 1.0) for item_code in range(10)]

print('策略三:訂單中的不同商品達到10個或以上時提供7%折扣')
print(Order(joe, long_order, LargeOrderPromo()))
print(Order(joe, cart, LargeOrderPromo()))

輸出:

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

3、使用函數實現策略模式

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

from collections import namedtuple

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(self)
 return self.total() - discount

 def __repr__(self):
 fmt = '<訂單 總價: {:.2f} 實付: {:.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


joe = 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('策略二:單個商品為20個或以上時提供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('策略三:訂單中的不同商品達到10個或以上時提供7%折扣')
print(Order(joe, long_order, large_order_promo))
print(Order(joe, cart, large_order_promo))

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

值得注意的是,《設計模式:可復用面向對象軟件的基礎》一書的作者指出:“策略對象通常是很好的享元?!?享元是可共享的對象,可以同時在多個上下文中使用。共享是推薦的做法,這樣不必在每個新的上下文(這里是 Order 實例)中使用相同的策略時不斷新建具體策略對象,從而減少消耗。因此,為了避免 [策略模式] 的運行時消耗,可以配合 [享元模式] 一起使用,但這樣,代碼行數和維護成本會不斷攀升。

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

以上就是詳解Python設計模式之策略模式的詳細內容,更多關于Python 策略模式的資料請關注腳本之家其它相關文章!

相關文章

  • 關于Numpy中數組維度的理解

    關于Numpy中數組維度的理解

    這篇文章主要介紹了關于Numpy中數組維度的理解,多維Numpy數組也可以叫張量(tensor),當前所有機器學習系統(tǒng)都是使用張量作為基本數據結構,張量是一個數據容器,它包含的數據幾乎是數值數據,因此它也是數字的容器,需要的朋友可以參考下
    2023-09-09
  • 使用python實現深度優(yōu)先遍歷搜索(DFS)的示例代碼

    使用python實現深度優(yōu)先遍歷搜索(DFS)的示例代碼

    深度優(yōu)先搜索算法(Depth-First-Search,DFS)是一種用于遍歷或搜索樹或圖的算法,沿著樹的深度遍歷樹的節(jié)點,盡可能深的搜索樹的分支,本文給大家介紹了如何基于python實現深度優(yōu)先遍歷搜索(DFS),需要的朋友可以參考下
    2024-01-01
  • 7個實用的Python自動化代碼別再重復造輪子了

    7個實用的Python自動化代碼別再重復造輪子了

    關于Python有一句名言:不要重復造輪子,給大家分享經過Python3.6.4調試通過的代碼,感興趣的朋友跟隨小編一起看看吧
    2023-11-11
  • Python?解析獲取?URL?參數及使用步驟

    Python?解析獲取?URL?參數及使用步驟

    這篇文章主要介紹了Python?解析獲取?URL?參數及使用,本文分步驟通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-06-06
  • python自動化發(fā)送郵件實例講解

    python自動化發(fā)送郵件實例講解

    在本篇文章里小編給大家分享了一篇關于python自動化發(fā)送郵件實例講解內容,有興趣的朋友們可以學習參考下。
    2021-01-01
  • Win10環(huán)境python3.7安裝dlib模塊趟過的坑

    Win10環(huán)境python3.7安裝dlib模塊趟過的坑

    這篇文章主要介紹了Win10環(huán)境python3.7安裝dlib模塊趟過的坑,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-08-08
  • 檢測tensorflow是否使用gpu進行計算的方式

    檢測tensorflow是否使用gpu進行計算的方式

    今天小編就為大家分享一篇檢測tensorflow是否使用gpu進行計算的方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • 能讓Python提速超40倍的神器Cython詳解

    能讓Python提速超40倍的神器Cython詳解

    今天帶大家了解一下能讓Python提速超40倍的神器,文章圍繞著神器Cython展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • Python 彈窗設計小人發(fā)射愛心

    Python 彈窗設計小人發(fā)射愛心

    今天小編就為大家分享一篇使用Python畫出小人發(fā)射愛心的代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-09-09
  • 在Python中使用PIL模塊處理圖像的教程

    在Python中使用PIL模塊處理圖像的教程

    這篇文章主要介紹了在Python中使用PIL模塊處理圖像的教程,PIL模塊在Python編程中也是十分常用的模塊,示例代碼基于Python2.x版本,需要的朋友可以參考下
    2015-04-04

最新評論