欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > 【设计模式】2.策略模式

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

2025/6/13 19:59:13 来源:https://blog.csdn.net/weixin_39190382/article/details/148516116  浏览:    关键词:【设计模式】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 屏蔽底层细节,使客户端更纯粹

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词