Python设计模式: 最佳的"策略"模式实践代码

Python设计模式: 最佳的"策略"模式实践代码

今天抽空看了下流畅的python,发现里面介绍了不少python自带的库的使用实例,用起来非常的优雅。

平时用Python来写爬虫比较多,所以最近一直在看设计模式的内容。刚好这本书里面有一章单独讲设计模式的,讲的还不错,特意摘录出来。

这段代码的需求背景是电商平台常用的促销策略:

  1. 用户的积分超过1000时,订单总价优惠5%的金额
  2. 购买商品的种类超过10种时,订单总价优惠7%的金额
  3. 单个商品购买数量超过20件时,该商品获得10%的折扣

具体代码如下:

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

    def __repr__(self):
        fmt = '<Order total: {:.2f} due: {:.2f}>'
        return fmt.format(self.total(), self.due())


promos = []


def promotion(promo_func):
    promos.append(promo_func)
    return promo_func


@promotion
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


@promotion
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


@promotion
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


def best_promo(order):
    return max(promo(order) for promo in promos)


# # 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>
#     best promo========================================
#     >>> Order(joe, long_order, best_promo)
#     <Order total: 10.00 due: 9.30>
#     >>> Order(joe, banana_cart, best_promo)
#     <Order total: 30.00 due: 28.50>
#     >>> Order(ann, cart, best_promo)
#     <Order total: 42.00 due: 39.90>
# # END STRATEGY_TESTS
# """
# BEGIN STRATEGY

这段代码得益于装饰器的使用,实现起来非常优雅,而且逻辑清晰、代码简洁,仅用了77行代码,就实现了策略模式。

但是,这个代码是经过了3次迭代、优化之后的。

第一版:使用ABC抽象基类来实现

在第一个版本中,用了ABC抽象基类来实现,代码非常的啰嗦,感觉像在写JAVA

# 这里只贴核心逻辑代码
from abc import ABC, abstractmethod

class Promotion(ABC):  # 策略:抽象基类

    @abstractmethod
    def discount(self, order):
        """Return discount as a positive dollar amount"""


class FidelityPromo(Promotion):  # 第一个策略
    """5% discount for customers with 1000 or more fidelity points
    拥有1000或更高积分的客户可享受5%的折扣
    """

    def discount(self, order):
        return order.total() * .05 if order.customer.fidelity >= 1000 else 0


class BulkItemPromo(Promotion):  # 第二个策略
    """10% discount for each LineItem with 20 or more units
    单件商品购买超过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):  # 第三个策略
    """7% discount for orders with 10 or more distinct items
    购买商品的各类超过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

第二版:使用函数实现,更加扁平化,可复用

def fidelity_promo(order):
    """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

# BEGIN STRATEGY_BEST

promos = [fidelity_promo, bulk_item_promo, large_order_promo]  # <1>

def best_promo(order):  # <2>
    """Select best discount available
    """
    return max(promo(order) for promo in promos)  # <3>

好一些,主要的变动是抽象类撤掉了,改成函数来使用,实现更加的扁平化。而且不用实例化那么多对象。

第三版:把促销逻辑封装到一个模块当中

import inspect
import promotions

# 把上面那3个促销策略代码挪到promotions模块中
# 这个模块里只有这3个函数
promos = [func for name, func in inspect.getmembers(promotions, inspect.isfunction)]

def best_promo(order):
    """Select best discount available
    """
    return max(promo(order) for promo in promos)

其实第三版已经很优雅了,所有的促销逻辑全部都封装到promotions中,以后要增加新的促销策略,只需要去改promotions文件里面的代码就好了。

参考资料:

  1. Sample code for Chapter 6 - "Design patterns with first class functions"
posted @ 2019-11-19 13:48  seozed  阅读(445)  评论(0编辑  收藏  举报