Python 重构“策略”模式:用函数简化设计模式的实践

在软件设计中,设计模式是解决问题的通用模板。但随着编程语言特性的发展,某些经典模式可以通过更简洁的方式实现。本文以电商促销折扣场景为例,演示如何通过函数重构"策略"模式,减少代码量并提升可维护性。

经典策略模式实现

  • 核心概念
    上下文(Context):订单(Order)类,负责计算总价和应用折扣。
  • 策略接口(Strategy):
    抽象类Promotion,定义discount方法。
  • 具体策略(Concrete Strategies):
    三个子类分别实现不同折扣规则。
python 复制代码
class Promotion(ABC):
    @abstractmethod 
    def discount(self, order):
        """返回折扣金额(正值)"""
 
class FidelityPromo(Promotion):
    def discount(self, order):
        return order.total()  * .05 if order.customer.fidelity  >= 1000 else 0 
  • 实现特点
    每个策略类仅包含一个方法,且无状态。
    需手动实例化策略对象并传递给订单。

函数重构策略模式

  • 核心思想
    将策略类转换为函数,利用Python的一等函数特性简化代码:
python 复制代码
def fidelity_promo(order):
    return order.total()  * .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()  * .1
    return discount 

优势对比

经典模式 函数重构
需定义抽象类和多个子类 直接使用函数
每次使用需实例化对象 函数即用即调
代码行数:40+行 代码行数:28行

动态选择最佳策略

简单实现

通过遍历函数列表计算最大折扣:

python 复制代码
promos = [fidelity_promo, bulk_item_promo, large_order_promo]
def best_promo(order):
    return max(promo(order) for promo in promos)

动态收集策略

利用模块内省自动发现所有策略函数:

python 复制代码
from inspect import isfunction 
promos = [func for name, func in getmembers(promotions, isfunction) 
          if name.endswith('_promo')  and name != 'best_promo']

重构总结

维度 经典模式 函数重构
代码量 较多 显著减少
可维护性 需管理类继承关系 函数即策略,直观清晰
扩展性 新策略需新增类 新函数自动纳入

适用场景:当策略无状态且仅需单次计算时,函数重构能大幅提升开发效率。若需维护策略状态,则仍需使用类实现。


通过这一重构实践,我们不仅减少了代码冗余,还充分利用了Python的函数特性,展现了设计模式与语言特性的结合之美。

相关推荐
鲸屿19510 分钟前
python之socket网络编程
开发语言·网络·python
里昆14 分钟前
【AI】Tensorflow在jupyterlab中运行要注意的问题
人工智能·python·tensorflow
AI视觉网奇16 分钟前
pycharm 最新版上一次编辑位置
python
2401_8288906438 分钟前
使用 BERT 实现意图理解和实体识别
人工智能·python·自然语言处理·bert·transformer
中电金信2 小时前
中电金信:AI重构测试体系·智能化时代的软件工程新范式
人工智能·重构·软件工程
多恩Stone2 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc
宁静致远20212 小时前
【C++设计模式】第三篇:观察者模式(别名:发布-订阅模式、模型-视图模式、源-监听器模式)
c++·观察者模式·设计模式
xiaopengbc2 小时前
在 Python 中实现观察者模式的具体步骤是什么?
开发语言·python·观察者模式
Python大数据分析@2 小时前
python用selenium怎么规避检测?
开发语言·python·selenium·网络爬虫