雖然設計模式與語言無關,但這並不意味着每個模式都能在每一門語言中使用。《設計模式:可複用面向對象軟件的基礎》一書中有 23 個模式,其中有 16 個在動態語言中「不見了,或者簡化了」。算法
策略模式:定義一系列算法,把它們一一封裝起來,而且使它們之間能夠相互替換。此模式讓算法的變化不會影響到使用算法的客戶。設計模式
電商領域有個使用「策略」模式的經典案例,即根據客戶的屬性或訂單中的商品計算折扣。app
假如一個網店制定了下述折扣規則。ide
簡單起見,咱們假定一個訂單一次只能享用一個折扣。函數
UML類圖以下:post
Promotion 抽象類提供了不一樣算法的公共接口,fidelityPromo、BulkPromo 和 LargeOrderPromo 三個子類實現具體的「策略」,具體策略由上下文類的客戶選擇。設計
在這個示例中,實例化訂單(Order 類)以前,系統會以某種方式選擇一種促銷折扣策略,而後把它傳給 Order 構造方法。具體怎麼選擇策略,不在這個模式的職責範圍內。(選擇策略可使用工廠模式。)code
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()))
輸出:orm
策略一:爲積分爲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>
在傳統策略模式中,每一個具體策略都是一個類,並且都只定義了一個方法,除此以外沒有其餘任何實例屬性。它們看起來像是普通的函數同樣。的確如此,在 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 實例)中使用相同的策略時不斷新建具體策略對象,從而減小消耗。所以,爲了不 [策略模式] 的運行時消耗,能夠配合 [享元模式] 一塊兒使用,但這樣,代碼行數和維護成本會不斷攀升。
在複雜的狀況下,須要具體策略維護內部狀態時,可能須要把「策略」和「享元」模式結合起來。可是,具體策略通常沒有內部狀態,只是處理上下文中的數據。此時,必定要使用普通的函數,別去編寫只有一個方法的類,再去實現另外一個類聲明的單函數接口。函數比用戶定義的類的實例輕量,並且無需使用「享元」模式,由於各個策略函數在 Python 編譯模塊時只會建立一次。普通的函數也是「可共享的對象,能夠同時在多個上下文中使用」。