电商领域有个功能明显可以使用“策略”模式,即根据客户的属性或订单中的商品计算折扣。
假如一个网店制定了下述折扣规则。
有 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 = 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) : # 策略:抽象基类 @abstractmethod def discount(self, order): """返回折扣金额(正值)""" pass class FidelityPromo(Promotion): # 第一个具体策略 """为积分为1000或以上的顾客提供5%折扣""" def discount(self, order): return order.total() * .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() * .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() * .07 return 0
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 = 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 = '<Order total: {:.2f} due: {:.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
3.选择最佳策略
promos = [globals()[name] for name in globals() if name.endswith('_promo') and name != 'best_promo'] #globals返回一个字典,始终针对当前模块 def best_promo(order): """选择可用的最佳折扣""" return max(promo(order) for promo in promos)
或者使用inspect
promos = [func for name, func in inspect.getmembers(promotions, inspect.isfunction)] def best_promo(order): """选择可用的最佳折扣""" return max(promo(order) for promo in promos)
4.使用装饰器改进“策略”模式
promos = [] def promotion(promo_func): promos.append(promo_func) return promo_func @promotion def fidelity(order): """为积分为1000或以上的顾客提供5%折扣""" return order.total() * .05 if order.customer.fidelity >= 1000 else 0 @promotion def bulk_item(order): """单个商品为20个或以上时提供10%折扣""" discount = 0 for item in order.cart: if item.quantity >= 20: discount += item.total() * .1 return discount @promotion def large_order(order): """订单中的不同商品达到10个或以上时提供7%折扣""" distinct_items = {item.product for item in order.cart} if len(distinct_items) >= 10: return order.total() * .07 return 0 def best_promo(order): """选择可用的最佳折扣""" return max(promo(order) for promo in promos)