应用场景: 电商领域根据客户的属性或订单中的商品计算折扣
折扣规则:
- 有 1000 或以上积分的顾客,每个订单享 5% 折扣。
- 同一订单中,单个商品的数量达到 20 个或以上,享 10% 折扣。
- 订单中的不同商品达到 10 个或以上,享 7% 折扣
假定一个订单一次只能享用一个折扣
1. 面向对象版的策略模式
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 = 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):
"""Return discount as a positive dollar amount"""
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
def run():
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(Order(joe, cart, FidelityPromo()))
print(Order(ann, cart, FidelityPromo()))
banane_cart = [LineItem('banana', 30, .5),
LineItem('apple', 10, 1.5)]
print(Order(joe, banane_cart, BulkItemPromo()))
long_order = [LineItem(str(item_code), 1, 1.0)
for item_code in range(10)]
print(Order(joe, long_order, LargeOrderPromo()))
if __name__ == '__main__':
run()
2. 函数版的策略模式
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 = 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 = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
def fidelity_promo(order):
return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0
def bulk_item_promo(order):
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * 0.1
return discount
def large_order_promo(order):
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * 0.07
return 0
def run():
print(Order(joe, cart, fidelity_promo))
print(Order(ann, cart, fidelity_promo))
print(Order(joe, banane_cart, bulk_item_promo))
print(Order(joe, long_order, large_order_promo))
if __name__ == '__main__':
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)]
banane_cart = [LineItem('banana', 30, .5),
LineItem('apple', 10, 1.5)]
long_order = [LineItem(str(item_code), 1, 1.0)
for item_code in range(10)]
run()
计算最优折扣
promos = [fidelity_promo, bulk_item_promo, large_order_promo]
def best_promo(order):
"""选择可用的最佳折扣"""
return max(promo(order) for promo in promos)
def best_run():
print(Order(joe, long_order, best_promo))
print(Order(joe, banane_cart, best_promo))
print(Order(ann, cart, best_promo))
使用 inspect.getmembers
内省独立模块
import inspect
import promotions
# inspect.getmembers 获取对象(这里是模块)的属性
promos = [func for name, func in
inspect.getmembers(promotions, inspect.isfunction)]
promotions.py
里面是策略函数:
def fidelity_promo(order):
return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0
def bulk_item_promo(order):
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * 0.1
return discount
def large_order_promo(order):
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * 0.07
return 0
来源: 《流畅的Python》6.1节