案例分析:重构“策略”模式
《设计模式:可复用面向对象软件的基础》一书是这样概述“策略”模式的:
定义一系列算法,把它们一一封装起来,并且使它们可以相互替换。本模式使得算法可以独立于使用它的客户而变化。
假如一个网店制定了下述折扣规则:
- 有 1000 或以上积分的顾客,每个订单享 5% 折扣。
- 同一订单中,单个商品的数量达到 20 个或以上,享 10% 折扣。
- 订单中的不同商品达到 10 个或以上,享 7% 折扣。
- 简单起见,我们假定一个订单一次只能享用一个折扣
“策略”模式的 UML 类图见图 6-1,其中涉及下列内容。
內容 | 說明 |
---|---|
上下文 | 把一些计算委托给实现不同算法的可互换组件,它提供服务。在这个电商示例中,上下文是Order,它会根据不同的算法计算促销折扣。 |
策略 | 实现不同算法的组件共同的接口。在这个示例中,名为 Promotion 的抽象类扮演这个角色。 |
具体策略 | “策略”的具体子类。fidelityPromo、BulkPromo 和 LargeOrderPromo 是这里实现的三个具体策略。 |
实现 Order 类,支持插入式折扣策略
# classic_strategy.py
# Strategy pattern -- classic implementation
"""
# BEGIN CLASSIC_STRATEGY_TESTS
>>> joe = Customer(‘John Doe‘, 0) # <1>
>>> ann = Customer(‘Ann Smith‘, 1100)
>>> cart = [LineItem(‘banana‘, 4, .5), # <2>
... LineItem(‘apple‘, 10, 1.5),
... LineItem(‘watermellon‘, 5, 5.0)]
>>> Order(joe, cart, FidelityPromo()) # <3>
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, FidelityPromo()) # <4>
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem(‘banana‘, 30, .5), # <5>
... LineItem(‘apple‘, 10, 1.5)]
>>> Order(joe, banana_cart, BulkItemPromo()) # <6>
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0) # <7>
... for item_code in range(10)]
>>> Order(joe, long_order, LargeOrderPromo()) # <8>
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, LargeOrderPromo())
<Order total: 42.00 due: 42.00>
# END CLASSIC_STRATEGY_TESTS
"""
# BEGIN CLASSIC_STRATEGY
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: # the Context
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): # the Strategy: an Abstract Base Class
@abstractmethod
def discount(self, order):
"""Return discount as a positive dollar amount"""
class FidelityPromo(Promotion): # first Concrete Strategy
"""5% discount for customers with 1000 or more fidelity points"""
def discount(self, order):
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
class BulkItemPromo(Promotion): # second Concrete Strategy
"""10% discount for each LineItem with 20 or more units"""
def discount(self, order):
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * .1
return discount
class LargeOrderPromo(Promotion): # third Concrete Strategy
"""7% discount for orders with 10 or more distinct items"""
def discount(self, order):
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
# END CLASSIC_STRATEGY
使用函数实现“策略”模式
每个具体策略都是一个类,而且都只定义了一个方法,即discount。此外,策略实例没有状态(没有实例属性)。
提示
當一個類只有一個函數時,應該將其重構成一個函數。因爲函數的開銷比類小很多。
# strategy.py
# Strategy pattern -- function-based implementation
"""
# BEGIN STRATEGY_TESTS
>>> joe = Customer(‘John Doe‘, 0) # <1>
>>> ann = Customer(‘Ann Smith‘, 1100)
>>> cart = [LineItem(‘banana‘, 4, .5),
... LineItem(‘apple‘, 10, 1.5),
... LineItem(‘watermellon‘, 5, 5.0)]
>>> Order(joe, cart, fidelity_promo) # <2>
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, fidelity_promo)
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem(‘banana‘, 30, .5),
... LineItem(‘apple‘, 10, 1.5)]
>>> Order(joe, banana_cart, bulk_item_promo) # <3>
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, long_order, large_order_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, large_order_promo)
<Order total: 42.00 due: 42.00>
# END STRATEGY_TESTS
"""
# BEGIN STRATEGY
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: # the Context
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) # <1>
return self.total() - discount
def __repr__(self):
fmt = ‘<Order total: {:.2f} due: {:.2f}>‘
return fmt.format(self.total(), self.due())
# <2>
def fidelity_promo(order): # <3>
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
def bulk_item_promo(order):
"""10% discount for each LineItem with 20 or more units"""
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * .1
return discount
def large_order_promo(order):
"""7% discount for orders with 10 or more distinct items"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
# END STRATEGY
选择最佳策略:简单的方式
promos = [fidelity_promo, bulk_item_promo, large_order_promo] # <1>promos 列出以函数实现的各个策略。
def best_promo(order):
"""Select best discount available
"""
return max(promo(order) for promo in promos)
但是有些重复可能会导致不易察觉的缺陷:若想添加新的促销策略,要定义相应的函数,还要记得把它添加到promos列表中;否则,当新促销函数显式地作为参数传给 Order 时,它是可用的,但是 best_promo 不会考虑它。
找出模块中的全部策略
promos = [globals()[name] for name in globals() # <1>迭代 globals() 返回字典中的各个 name。
if name.endswith(‘_promo‘) # <2>只选择以 _promo 结尾的名称。
and name != ‘best_promo‘] # <3>过滤掉 best_promo 自身,防止无限递归。
def best_promo(order):
"""Select best discount available
"""
return max(promo(order) for promo in promos) # <4>best_promo 内部的代码没有变化。
這裏需要注意的地方有:
- 策略模式所定義的函數結尾均是
_promo
- 不要忘記類
globals()
globals()
from pprint import pprint
def fun():
pass
dd = dict()
ll = list()
pprint(globals())
"""output
{‘__annotations__‘: {},
‘__builtins__‘: <module ‘builtins‘ (built-in)>,
‘__cached__‘: None,
‘__doc__‘: None,
‘__file__‘: ‘/home/yuanoung/Projects/fluent-python/other/test.py‘,
‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x7f35590ca080>,
‘__name__‘: ‘__main__‘,
‘__package__‘: None,
‘__spec__‘: None,
‘dd‘: {},
‘fun‘: <function fun at 0x7f35590f0ea0>,
‘ll‘: [],
‘pprint‘: <function pprint at 0x7f355735b840>}
"""