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

【设计模式】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 屏蔽底层细节,使客户端更纯粹

http://www.xdnf.cn/news/12738.html

相关文章:

  • 【网站建设】不同类型网站如何选择服务器?建站项目实战总结
  • AI智能体|扣子(Coze)搭建【公众号对标文章采集拆解】工作流
  • DeepSeek11-Ollama + Open WebUI 搭建本地 RAG 知识库全流程指南
  • windows10下搭建nfs服务器
  • 【分布式】分布式ID介绍和实现方案总结
  • 力扣算法题1
  • Vue部署到Nginx上及问题解决
  • 深入理解 React Hooks
  • 通过css实现正方体效果
  • 【免费数据】2005-2019年我国272个地级市的旅游竞争力多指标数据(33个指标)
  • C++11 右值引用
  • Pandas-如何正确将两张数据表进行合并
  • 自定义protoc-gen-go生成Go结构体,统一字段命名与JSON标签风格
  • 【Zephyr 系列 15】构建企业级 BLE 模块通用框架:驱动 + 事件 + 状态机 + 低功耗全栈设计
  • github开源协议选择
  • iview-admin静态资源js按需加载配置
  • STM标准库-TIM旋转编码器
  • JAVASCRIPT 前端数据库-V6--仙盟数据库架构-—-—仙盟创梦IDE
  • 深入浅出 Arrays.sort(DualPivotQuicksort):如何结合快排、归并、堆排序和插入排序
  • 2025年夏第九届河北工业大学程序设计校赛
  • Linux 上的 Tomcat 端口占用排查
  • 2025-06-08 思考-人被基因和社会关系双重制约
  • Psychopy音频的使用
  • 实验四:图像灰度处理
  • 自动化立体仓库堆垛机控制系统STEP7 OB1功能块
  • python打卡day48
  • 《解锁树莓派+Java:TinyML模型部署的性能飞升秘籍》
  • Java 面向对象进阶之多态:从概念到实践的深度解析
  • Windmill:开源开发者基础设施的革命者
  • Apache Spark详解