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

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

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

相关推荐
ting94520002 天前
Minimi 深度技术剖析:macOS 端侧全量上下文采集与 Claude 本地 RAG 联动架构详解
macos·架构·策略模式
Qimooidea3 天前
MacOS 平台 CAD 图纸翻译实战:从技术挑战到高效落地
macos·策略模式
张小姐的猫3 天前
【Linux】多线程 —— 线程池 | 单例模式 | 常见锁
linux·运维·服务器·c++·单例模式·设计模式·策略模式
铁锚4 天前
macOS 禁用 mediaanalysisd
macos·策略模式
Dr_eamboat5 天前
SpringBoot策略模式+工厂模式实战解析
linux·spring boot·策略模式
basketball6167 天前
设计模式入门:7. 策略模式详解 C++实现
c++·设计模式·策略模式
Java_2017_csdn10 天前
Java 策略模式(Strategy Pattern)-(二)
java·开发语言·策略模式
Java_2017_csdn10 天前
Java 策略模式(Strategy Pattern)-(一)
java·开发语言·策略模式
拾光Ծ10 天前
【Linux系统编程】线程池项目实战与基于策略模式的日志系统
linux·bash·线程池·策略模式·日志