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

我们先来假设一个场景:作为杂货店老板,你还需要根据不同季节或促销活动选择不同的定价策略。比如在淡季时,货物打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

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

相关推荐
意法半导体STM3215 天前
【官方原创】如何为STM32CubeMX2配置Visual Studio Code配置方案
vscode·stm32·单片机·嵌入式硬件·策略模式·stm32cubemx·嵌入式开发
山东点狮信息科技有限公司15 天前
企业级 MES 制造执行系统架构设计与实践
spring cloud·性能优化·系统架构·策略模式·点狮
zzqssliu16 天前
基于策略模式与责任链的代购商品多源采集架构实战
架构·策略模式
mxpan17 天前
macOS 13+ 上使用 macFUSE + NTFS-3G 读写 NTFS 移动硬盘技术说明
macos·策略模式
折哥的程序人生 · 物流技术专研17 天前
Java 23 种设计模式:从踩坑到精通 | 番外:编排器+策略模式在多平台电子面单中的实战(含性能压测)
设计模式·策略模式·代码重构·java设计模式·编排器·电子面单·从踩坑到精通
忧云18 天前
2026年最新 Cursor 国内使用 DeepSeek API等各模型使用完整教程
ai编程·策略模式·cursor·byok·cursor使用国内大模型
AIex-YH18 天前
三域贯通11/12:生物制造的“死亡之谷“,CDMO 是桥还是船?
运维·制造·策略模式
回忆2012初秋18 天前
【Nginx】原理、配置与运维实战(2)
运维·nginx·策略模式
怎么没有名字注册了啊19 天前
macOS 基于 CSDN GitCode + Homebrew Tap 发布 Qt .app 二进制程序通用教程(homebrew 安装自己的软件)
策略模式·homebrew·formula·ruhy
坏小虎20 天前
macOS 安装 Ghostty 终端完整教程:环境、依赖与美化配置
macos·策略模式