使用一等函数实现设计模式
策略模式
经典的策略模式
策略模式(Strategy Pattern):定义一系列算法,将每一个算法封装起来,并让它们可以相互替换。策略模式让算法独立于使用它的客户而变化,也称为政策模式(Policy)。
-
模式结构
- Context: 环境类
- Strategy: 抽象策略类
- ConcreteStrategy: 具体策略类
-
策略模式实现打折功能
from abc import ABC, abstractmethod from collections import namedtuple Customer = namedtuple('Customer', 'name fidelity') #灵活使用namedtuple创建简单的类 class LineItem: def __init__(self, product, quantity, price): self.produt = 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 self.__total self.__due def total(self): 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) self.__due = self.total - discount return self.__due def __repr__(self): fmt = '<Order total: {:.2f} due:{:.2f}>' return fmt.format(self.total(), self.due()) # 策略:抽象基类, Promotion定义为抽象基类(Abstract BaseClass,ABC),这么做是为了使用 @abstractmethod 装饰器,从而明确表明所用的模式。 class Promotion(ABC): @abstractmethod def discount(self, order): """返回折扣金额(正值)""" 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
使用函数实现”策略“模式
上一节中传统的策略模式中,每个策略都是一个类并且只定义了一个方法,此外策略实例没有实例属性。因此看起来更像一个函数,因此基于Python中函数可作为一等对象,可直接将具体类策略修改为具体函数策略。
from collections import namedtuple
Customer = namedtuple('Customer', 'name fidelity')
class LineItem:
def __init__(self, product, quantity, price):
self.produt = 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
self.__total
self.__due
def total(self):
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) #此时只需要调用函数即可,不用再调用实例方法
self.__due = self.total - discount
return self.__due
def __repr__(self):
fmt = '<Order total: {:.2f} due:{:.2f}>'
return fmt.format(self.total(), self.due())
def FidelityPromo(order): # 第一个具体策略,并且所有策略都为函数
"""为积分为1000或以上的顾客提供5%折扣"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
def BulkItemPromo(order):
"""单个商品为20个或以上时提供10%折扣"""
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * .1
return discount
def LargeOrderPromo(order):
"""订单中的不同商品达到10个或以上时提供7%折扣"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
策略模式完善
globals()
返回一个字典,表示当前的全局符号表。这个符号表始终针对当前模块(对函数或方法来说,是指定义它们的模块,而不是调用它们的模块)。
找出全部策略并返回最大折扣
promos = [globals[name] for name in globals()
if name.endswith('Promo')]
def best_promo(order):
return max(promo(order) for promo in promos)
命令模式
命令模式(Command Pattern):将一个请求封装为一个对象,从而使我们可用不同的请求对客户进行参数化;对请求排队或者记录请求日志,以及支持可撤销的操作。命令模式是一种对象行为型模式,其别名为动作(Action)模式或事务(Transaction)模式。
class MacroCommand:
"""一个执行一组命令的命令"""
def __init__(self, commands):
self.commands = list(commands)
def __call__(self):
for command in self.commands:
command()
总结
感觉受限于自己的知识水平,这一章没有写太多,期待在学习设计模式后可以用Pythonic的方式实现一下可以实现的设计模式。