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

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

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

相关推荐
沪上企服通18 小时前
代账数据的可移植性设计:开放接口、账套导出与 exit strategy 工程笔记(上海 5 家样本对照)
笔记·策略模式
码匠许师傅20 小时前
【设计模式精讲】26.策略模式(Strategy)
c++·设计模式·策略模式·uml
++==4 天前
基于策略模式的应用层协议支持
策略模式
Java后端的Ai之路4 天前
23、Python - 策略模式
linux·python·策略模式
程序员夏洛6 天前
什么是策略模式?一般用在什么场景?
策略模式
user_admin_god7 天前
数据采集/交换系统设计经验
spring boot·spring·策略模式
Nontee14 天前
Quartz 集群 + 策略模式:逾期预警推送系统设计实录
linux·服务器·策略模式
二炮手亮子15 天前
从 BIO、NIO、AIO 到多路复用与 Netty
策略模式·nio
cui_hao_nan16 天前
大模型负责“聪明“,策略模式负责“执行“:智能配图系统如何自动选择图片来源
策略模式·ai开发
阿萨德528号19 天前
npm 包发布实战指南:从零发布、更新迭代到版本治理
前端·npm·策略模式