当前位置: 首页 > news >正文

【设计模式】2.策略模式

every blog every motto: You can do more than you think.
https://blog.csdn.net/weixin_39190382?type=blog

0. 前言

商场收银软件为例

1. 基础版

total = 0def click_ok(price,num):tot = price * numtotal += totprint('合计:', total)

增加打折

total = 0def click_ok(price,num,dis_num):tot = price * numtotal += totif dis_num == '0': # 正常收费passelif dis_num == '8':total *= 0.8elif dis_num == '7':total *= 0.7elif dis_num == '5':total *= 0.5print('合计:', total)

2. 简单工厂

20250511215044

class cashSuper(ABC):"""收取现金超类"""@abstractmodedef acceptcash(money):"""接收现金抽象类"""passclass cashNormal(cashSuper):"""正常收费子类"""def acceptcash(money):return moneyclass cashRebate(cashSuper):"""打折收费子类"""def cash_rebate(rebate):"""打折"""self.rebate = rebatedef acceptcash(money):return money * self.rebateclass cashReturn(cashSuper):"""返利收费条件"""def cash_return(condition, moneyreturn):self.condition = condition # 返利条件self.moneyreturn = moneyreturndef accpetcash(money):if money >= self.condition:return money - (money-self.condition)*self.moneyreturnreturn money
class CashFactory:@staticmethoddef create_cash_accept(type_str) -> CashSuper:cs = Noneif type_str == "正常收费":cs = CashNormal()elif type_str == "满 300 返 100":cr1 = CashReturn("300", "100")cs = cr1elif type_str == "打 8 折":cr2 = CashRebate("0.8")cs = cr2return cs

3. 策略模式

20250511221305

class cashSuper(ABC):"""收取现金超类"""@abstractmodedef acceptcash(money):"""接收现金抽象类"""passclass cashNormal(cashSuper):"""正常收费子类"""def acceptcash(money):return moneyclass cashRebate(cashSuper):"""打折收费子类"""def cash_rebate(rebate):"""打折"""self.rebate = rebatedef acceptcash(money):return money * self.rebateclass cashReturn(cashSuper):"""返利收费条件"""def cash_return(condition, moneyreturn):self.condition = condition # 返利条件self.moneyreturn = moneyreturndef accpetcash(money):if money >= self.condition:return money - (money-self.condition)*self.moneyreturnreturn money
class CashContext:def __init__(self, cash_super:cashSuper):self.cs = cash_super  # 通过构造方法传入具体的收费策略def get_result(self, money):return self.cs.accept_cash(money)  # 根据收费策略计算结果

需要再客户端判断哪种收费方式,可进行如下修改

4. 策略和简单工厂结合

这样就不用再客户端里面写分类代码了。

# 上下文类
class CashContext:def __init__(self, type: str):self.cs = Noneif type == "正常收费":self.cs = CashNormal()elif type == "满 300 返 100":self.cs = CashReturn("300", "100")elif type == "打 8 折":self.cs = CashRebate("0.8")else:raise ValueError("无效的收费类型")def get_result(self, money: float) -> float:return self.cs.accept_cash(money)

5. 简单工厂 VS 策略和简单工厂结合

客户端

简单工厂

# 客户端代码
from cash_factory import CashFactory, CashSuper  # 必须导入父类 CashSupertype = "满 300 返 100"
money = 350# 客户端需要显式调用工厂,并知道返回的是 CashSuper 类型
csuper = CashFactory.create_cash_accept(type)  # 客户端知道 CashSuper 存在
result = csuper.accept_cash(money)            # 客户端需了解 accept_cash() 方法

策略和简单工厂结合

# 客户端代码
from cash_context import CashContext  # 仅需导入 CashContexttype = "满 300 返 100"
money = 350# 客户端只需与 CashContext 交互
csuper = CashContext(type)           # 完全隐藏 CashSuper 和 CashFactory
result = csuper.get_result(money)    # 统一方法名,隐藏具体实现

在简单工厂中,工厂方法的返回值类型是 CashSuper,客户端必须:

  1. 知道 CashSuper 是抽象父类

  2. 知道调用 accept_cash() 方法(如 csuper.accept_cash(money))

而策略+工厂模式通过 CashContext 封装了工厂和策略的细节,客户端只需调用统一的 get_result()。

小结:

  1. 简单工厂的耦合体现在:客户端需直接操作 CashSuper 的接口

  2. 策略+工厂的改进:通过 CashContext 屏蔽底层细节,使客户端更纯粹

相关文章:

  • Python Selenium登录网易邮箱
  • springboot启动mapper找不到方法对应的xml
  • 分形几何在医学可视化中的应用:从理论到Python实战
  • 支持selenium的chrome driver更新到137.0.7151.68
  • 【CSS-8】深入理解CSS选择器权重:掌握样式优先级的关键
  • LLMs 系列科普文(11)
  • U盘安装ubuntu系统
  • HNCTF 2025 Just Ping Write-up
  • 云备份项目
  • 如何基于CMake构建STM32、GD32等MCU开发环境?
  • 基于Java Web的校园失物招领平台设计与实现
  • AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年6月8日第102弹
  • 从 Vue 2.0 进阶到 Vue 3.0 的核心技术解析指南
  • Agent短期记忆的几种持久化存储方式
  • 随便刷刷web题
  • JUC笔记(上)-复习 涉及死锁 volatile synchronized CAS 原子操作
  • 为什么 AI 理解不了逻辑问题?
  • Linux系统之grub-mkrescue详解
  • 永磁同步电机参数辨识算法--IPMSM拓展卡尔曼滤波全参数辨识
  • 免费批量去水印工具 - 针对文心一言生成图片
  • 网站设计语言有哪些/百度竞价最低点击一次多少钱
  • 小说网站搭建教程/怎么做关键词优化排名
  • 有帮忙做儿童房设计的网站吗/今日网站收录查询
  • dw外部网站链接怎么做/看到招聘游戏推广员千万别去
  • 怎么在网站做系统/百度竞价最低点击一次多少钱
  • 导航类网站怎么做排名/百度产品推广