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

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

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

相关推荐
AC赳赳老秦11 小时前
OpenClaw与Excel联动:批量读取/写入数据,生成可视化报表
开发语言·python·excel·产品经理·策略模式·deepseek·openclaw
lwf0061642 天前
解决macOS .dmg 文件无法安装问题
macos·策略模式
草莓熊Lotso3 天前
手搓工业级 C++ 线程安全日志系统:基于策略模式解耦,兼容 glog 使用风格
linux·运维·服务器·数据库·c++·安全·策略模式
蜜汁小强3 天前
macOS 开发者的 tmux 实战配置:分屏导航、vi 复制模式与系统剪贴板一站打通
macos·策略模式
AC赳赳老秦4 天前
OpenClaw与系统环境冲突:Windows/Mac系统兼容问题解决指南
开发语言·python·产品经理·策略模式·pygame·deepseek·openclaw
筱璦4 天前
C#期货分仓、策略交易模拟演示系统(含资源下载)
开发语言·c#·策略模式·量化交易·期货交易
艾莉丝努力练剑4 天前
【Linux线程】Linux系统多线程(八):<策略模式>日志系统的封装实现
linux·运维·服务器·c++·学习·策略模式
云空6 天前
《OpenClaw(macOS版)部署与使用中的安全问题及解决方案》
安全·macos·策略模式
Rsun045517 天前
13、Java 策略模式从入门到实战
java·bash·策略模式