策略模式的思想的经典案例分析
我们先来假设一个场景作为杂货店老板你还需要根据不同季节或促销活动选择不同的定价策略。比如在淡季时货物打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好了本文到这里就结束了希望认真阅读全文的小伙伴都能有所收获哦
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2547432.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!