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

Strategy_Mode

文章目录

  • 1. 策略模式
  • 2. 代码实现:

1. 策略模式

策略模式主要用于一种行为模式,方便在算法的运行中不断的切换策略,有抽象类和具体类,是一种非常实用的设计方法。有利于程序的框架搭建和扩展

2. 代码实现:

  • python 代码
from abc import ABC, abstractmethodclass Strategy(ABC):@abstractmethoddef execute(self, price):passclass DiscountStrategy(Strategy):def execute(self, price):return price * 0.9class NoDiscountStrategy(Strategy):def execute(self, price):return priceclass PromotionContext:def __init__(self, strategy: Strategy):self._strategy = strategydef set_strategy(self, strategy: Strategy):self._strategy = strategydef apply_discount(self, price):apply_discount = self._strategy.execute(price)print(f"{self._strategy.__class__.__name__} is for {apply_discount}")if __name__ == "__main__":promotion = PromotionContext(DiscountStrategy())promotion.apply_discount(100)promotion.set_strategy(NoDiscountStrategy())promotion.apply_discount(200)
  • 运行结果:
DiscountStrategy is for 90.0
NoDiscountStrategy is for 200

http://www.mrgr.cn/news/58153.html

相关文章:

  • 解决javaee maven package时一直TEST报错的问题
  • Docker部署MySQL主从复制
  • Linux等保测评需要用到的命令
  • w外链如何跳转微信小程序
  • UDP协议学习
  • 重学SpringBoot3-Spring WebFlux之HttpHandler和HttpServer
  • vue中使用 html2canvas绘制图片并下载
  • 一些关于 WinCC Comfort 和 WinCC Advanced 脚本编程语言 VBS 的实用技巧
  • 《Python游戏编程入门》注-第3章3
  • TinyC编译器6—用 flex 做词法分析
  • JVM学习之路(3)类加载器
  • 正则表达式基础知识
  • 【Docker】Dockerfile 用于组装镜像的指令都有啥?
  • Robot Framework接口自动化测试案例
  • Shell 编程-Shell 函数你学会了吗?
  • 【含开题报告+文档+PPT+源码】社区医院预约挂号看病系统的设计与实现
  • python回调函数概念及应用场景举例
  • 于Java语言 Netty通讯框架的云块充协议1.5_云快充协议1.6_云快充协议1.4_云快充协议
  • Flutter TextField和Button组件开发登录页面案例
  • 【赵渝强老师】Hive的内部表与外部表
  • TreeMap详解
  • 产品推介——LSOP4晶体管光耦KL101X
  • web 请求日志追踪(traceID)提升运维效率
  • Nexpose 6.6.274 发布下载,新增功能概览
  • 华为OD机试 - 创建二叉树(Java 2024 E卷 200分)
  • 基于Java+SpringBoot+Vue的宠物咖啡馆平台的设计与实现