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

策略模式的思想的经典案例分析

我们先来假设一个场景:作为杂货店老板,你还需要根据不同季节或促销活动选择不同的定价策略。比如在淡季时,货物打9折销售。大批量采购时,提供85折优惠。

实际上,这就是策略模式的思想

// 定义策略接口 interface PricingStrategy { double calculatePrice(double originalPrice); } // 定义具体策略 class SeasonalDiscountStrategy implements PricingStrategy { @Override public double calculatePrice(double originalPrice) { return originalPrice * 0.9; // 10% discount } } class BulkPurchaseDiscountStrategy implements PricingStrategy { @Override public double calculatePrice(double originalPrice) { return originalPrice * 0.85; // 15% discount } } // 上下文 class GroceryStore { private PricingStrategy pricingStrategy; public GroceryStore(PricingStrategy strategy) { this.pricingStrategy = strategy; } public double calculateFinalPrice(double originalPrice) { return pricingStrategy.calculatePrice(originalPrice); } } // 使用示例 public class Main { public static void main(String[] args) { PricingStrategy seasonalDiscount = new SeasonalDiscountStrategy(); PricingStrategy bulkPurchaseDiscount = new BulkPurchaseDiscountStrategy(); GroceryStore store = new GroceryStore(seasonalDiscount); double finalPrice = store.calculateFinalPrice(100.0); System.out.println("Final price with seasonal discount: " + finalPrice); store = new GroceryStore(bulkPurchaseDiscount); finalPrice = store.calculateFinalPrice(10000.0); System.out.println("Final price with bulk purchase discount: " + finalPrice); } }

运行程序,输出如下:

Final price with seasonal discount: 90.0 Final price with bulk purchase discount: 8500.0

好了,本文到这里就结束了,希望认真阅读全文的小伙伴,都能有所收获哦!

http://www.jsqmd.com/news/689083/

相关文章:

  • 【AI智能体】Claude Code 集成Github CLI 实现高效项目协同使用详解
  • 谷歌神经机器翻译GNMT:从技术原理到行业变革
  • 一个异或的性质
  • FastAPI在MLOps中的安全认证实践与优化
  • 如何集成Hermes Agent/OpenClaw?2026年阿里云及Coding Plan配置保姆级攻略
  • 中医AI智能诊疗系统:7步免费部署仲景大语言模型的完整指南
  • 2026指纹浏览器与AI风控对抗技术实践:动态环境适配与行为模拟的完整方案
  • Windows系统优化新思路:告别手动调整,用WinUtil实现一键智能管理
  • 厦大847信号与系统状元447分上岸信院经验贴!
  • 2026年Hermes Agent/OpenClaw如何安装?阿里云及Coding Plan配置详细解读
  • ESP32通过WiFi+SBUS协议控制INAV飞控完整教程
  • 为什么越来越多女性创业者选择“玫瑰工程”?一个运营十五年的社区健康品牌深度解析 - GrowthUME
  • 华为MateBook 16重装Win10后,我这样配置开发环境(含软件清单与D盘路径规划)
  • 美的智能家电本地控制终极指南:告别云端依赖,享受稳定智能生活
  • 用InsightFace搞定人脸3D关键点检测:从68点到106点,再到姿态角Pitch/Yaw/Roll的实战解析
  • 浏览器指纹反检测技术深度解析——从内核层防护到行为拟真的全链路实现
  • 华北理工大学怎么样?从办学层次、学科特色、科研实力与升学优势详解
  • 2026年,邯郸性价比高的助贷公司哪家靠谱?一文为你揭晓答案! - GrowthUME
  • 避坑指南:RH850 RS-CANFD中断那些容易搞错的细节(附BusOff处理与FIFO配置)
  • Qt串口通信GUI卡顿?试试把QSerialPort丢到子线程里(附完整代码)
  • pheatmap进阶玩法:手把手教你用聚类结果反向导出排序后的数据表格
  • TensorRT-LLM中KV缓存优化技术解析与实践
  • 中国药科大学赵玉成、徐健/皖西学院韩邦兴ACS Catal|元胡中痕量高效镇痛活性成分左旋紫堇达明生物合成最后缺失步骤的解析(附招聘信息)
  • 关于 CSS 打印你应该知道的样式配置
  • 灰度发布在Agent迭代中的实践:流量分配、效果评估与快速回滚
  • 【JAVA网络面经】网络模型(OSI+TCP/IP)
  • 杂题选讲 2026.4.23 (5)
  • 终极小说下载器:200+网站一键保存,免费打造你的私人数字图书馆
  • 数学利器Maple 2025保姆级下载与安装流程详解
  • 告别MQTT.fx:用Node-RED可视化拖拽,轻松调试ESP8266与阿里云的数据流