Skip to content

使用一等函数实现设计模式

此笔记记录于《流畅的python》,大部分为其中的摘要,少部分为笔者自己的理解;笔记为jupyter转的markdown,原始版jupyter笔记在这个仓库

Gamma等人合著的《设计模式:可复用面向对象软件的基础》一书中有23个模式,其中有16个在动态语言中“不见了,或者简化了

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 = '<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
python
joe = Customer('John Doe', 0)
ann = Customer('Ann Smith', 1100)

cart = [
    LineItem('banana', 4, .5),
    LineItem('apple', 10, 1.5),
    LineItem('watermelon', 5, 5.0)
]
python
# 传入不同的促销策略函数进行计算  
print(Order(joe, cart, fidelity_promo))
<Order total: 42.00 due: 42.00>
python
print(Order(ann, cart, fidelity_promo))
<Order total: 42.00 due: 39.90>
python
banana_cart = [LineItem('banana', 30, .5), LineItem('apple', 10, 1.5)]
Order(joe, banana_cart, bulk_item_promo)
<Order total: 30.00 due: 28.50>
python
long_order = [LineItem(str(item_code), 1, 1.0) for item_code in range(20)]
Order(joe, long_order, large_order_promo)
<Order total: 20.00 due: 18.60>
python
Order(joe, cart, large_order_promo)
<Order total: 42.00 due: 42.00>
python
# 命令模式
class MacroCommand:
    """一个执行一组命令的命令"""

    def __init__(self, commands):
        self.commands = list(commands)  # ➊

    def __call__(self):
        for command in self.commands:  # ➋
            command()
            
# 复杂的“命令”模式(如支持撤销操作)可能需要更多,而不仅是简单的回调函数。