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

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

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

相关推荐
多加点辣也没关系11 小时前
设计模式-策略模式
java·设计模式·策略模式
悟051514 小时前
设计模式-策略模式
设计模式·策略模式
skilllite作者1 天前
UI-TARS-Desktop 智能桌面自动化实战指南
ui·自动化·策略模式
Java知识技术分享1 天前
策略模式的两种实现:抽象类和接口
java·spring·策略模式
丷丩5 天前
策略模式实战:GeoAI-UP中MVT发布器的可扩展架构设计
人工智能·架构·gis·策略模式·空间分析·geoai
码界奇点6 天前
基于策略模式的多数据源爬虫系统设计与实现
爬虫·python·毕业设计·策略模式·源代码管理·数据库系统
05候补工程师7 天前
【Python实战】告别杂乱脚本!基于SOLID原则与策略模式的 PDF转Word 批量处理系统
python·设计模式·pdf·word·策略模式
风筝在晴天搁浅9 天前
美团 手撕策略模式
策略模式
朗迹 - 张伟11 天前
用AI开发QT——Qt与Trae开发环境搭建
开发语言·qt·策略模式
A懿轩A12 天前
Ghostty:告别 Mac 毛坯终端,打造 2026 最丝滑的 Ghostty AI 开发驾驶舱——Claude Code 团队也在用
python·macos·策略模式