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

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

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

相关推荐
张小姐的猫2 天前
【Linux】网络编程 —— HTTP协议(上)
linux·运维·服务器·网络·http·单例模式·策略模式
笨拙的老猴子8 天前
小明学架构师的第七课:策略模式:告别if-else的选择困难症
系统架构·策略模式
肖爱Kun9 天前
C++设计策略模式
开发语言·c++·策略模式
折哥的程序人生 · 物流技术专研10 天前
Java 23 种设计模式:从踩坑到精通 | 番外:策略 vs 模板方法 —— 组合与继承的终极对决
java·策略模式·java面试·comparator·模版方法模式·java设计模式·从踩坑到精通
折哥的程序人生 · 物流技术专研10 天前
Java 23 种设计模式:从踩坑到精通 | 番外:状态 vs 策略 —— if-else 消除的两条路,你走对了吗?
java·spring·状态模式·策略模式·java面试·java设计模式·从踩坑到精通
ttod_qzstudio13 天前
【软考设计模式】策略模式:算法族的封装与动态切换精讲
设计模式·策略模式
儒雅的名14 天前
GoF设计模式——策略模式
设计模式·bash·策略模式
折哥的程序人生 · 物流技术专研14 天前
第4篇:Lambda 简化策略模式(Java 8+)
java·设计模式·策略模式·函数式编程·lambda·代码简化·扩充系列
在水一缸15 天前
拒绝被打扰:深度解析 macOS 进程守护与“反自动启动”攻防战
macos·策略模式·用户体验·进程守护·自动启动·系统权限
折哥的程序人生 · 物流技术专研15 天前
第3篇:手写促销策略引擎(满减、打折、立减)
java·设计模式·策略模式·开闭原则·编程实战·扩充系列·促销引擎