策略模式适用场景与具体实例解析

策略模式在多种场合下都能发挥其优势,尤其在需要根据不同条件或策略选择不同算法的场景中。下面是几个具体的适用场景及其对应的实例,以帮助进一步理解策略模式的实际应用。

1. 支付方式选择

在电子商务网站中,用户可以选择多种支付方式,如信用卡、PayPal、Apple Pay等。每种支付方式的处理流程可能不同,使用策略模式可以将这些支付方式抽象为策略,允许用户在运行时选择最合适的支付方式。

复制代码

Java

深色版本

复制代码
1// 策略接口
2public interface PaymentStrategy {
3    void pay(double amount);
4}
5
6// 具体策略:信用卡支付
7public class CreditCardPayment implements PaymentStrategy {
8    @Override
9    public void pay(double amount) {
10        // 处理信用卡支付逻辑
11        System.out.println("Paying $" + amount + " with Credit Card");
12    }
13}
14
15// 具体策略:PayPal支付
16public class PayPalPayment implements PaymentStrategy {
17    @Override
18    public void pay(double amount) {
19        // 处理PayPal支付逻辑
20        System.out.println("Paying $" + amount + " with PayPal");
21    }
22}
23
24// 上下文:购物车
25public class ShoppingCart {
26    private PaymentStrategy strategy;
27
28    public ShoppingCart(PaymentStrategy strategy) {
29        this.strategy = strategy;
30    }
31
32    public void checkout(double amount) {
33        strategy.pay(amount);
34    }
35}
36
37// 客户端代码
38public class Client {
39    public static void main(String[] args) {
40        ShoppingCart cart = new ShoppingCart(new CreditCardPayment());
41        cart.checkout(100.0); // 输出:Paying $100.0 with Credit Card
42        
43        cart = new ShoppingCart(new PayPalPayment());
44        cart.checkout(200.0); // 输出:Paying $200.0 with PayPal
45    }
46}
2. 排序算法选择

在数据处理中,不同的排序算法适用于不同的数据类型和大小。策略模式可以用来在运行时选择最适合当前数据集的排序算法。

复制代码

Java

深色版本

复制代码
1// 策略接口
2public interface SortStrategy {
3    void sort(int[] array);
4}
5
6// 具体策略:冒泡排序
7public class BubbleSort implements SortStrategy {
8    @Override
9    public void sort(int[] array) {
10        // 实现冒泡排序逻辑
11        System.out.println("Sorting with Bubble Sort");
12    }
13}
14
15// 具体策略:快速排序
16public class QuickSort implements SortStrategy {
17    @Override
18    public void sort(int[] array) {
19        // 实现快速排序逻辑
20        System.out.println("Sorting with Quick Sort");
21    }
22}
23
24// 上下文:数据处理器
25public class DataProcessor {
26    private SortStrategy strategy;
27
28    public DataProcessor(SortStrategy strategy) {
29        this.strategy = strategy;
30    }
31
32    public void process(int[] array) {
33        strategy.sort(array);
34    }
35}
36
37// 客户端代码
38public class Client {
39    public static void main(String[] args) {
40        DataProcessor processor = new DataProcessor(new BubbleSort());
41        processor.process(new int[]{5, 3, 2, 4, 1}); // 输出:Sorting with Bubble Sort
42        
43        processor = new DataProcessor(new QuickSort());
44        processor.process(new int[]{5, 3, 2, 4, 1}); // 输出:Sorting with Quick Sort
45    }
46}
3. 优惠策略选择

在营销活动中,商家可能提供多种优惠策略,如满减、打折、积分抵扣等。策略模式可以让商家根据商品类别或用户等级选择最优的优惠策略。

复制代码

Java

深色版本

复制代码
1// 策略接口
2public interface PromotionStrategy {
3    double applyPromotion(double price);
4}
5
6// 具体策略:满减优惠
7public class CashBackPromotion implements PromotionStrategy {
8    private final double threshold;
9    private final double discount;
10
11    public CashBackPromotion(double threshold, double discount) {
12        this.threshold = threshold;
13        this.discount = discount;
14    }
15
16    @Override
17    public double applyPromotion(double price) {
18        if (price >= threshold) {
19            return price - discount;
20        }
21        return price;
22    }
23}
24
25// 具体策略:打折优惠
26public class DiscountPromotion implements PromotionStrategy {
27    private final double discountRate;
28
29    public DiscountPromotion(double discountRate) {
30        this.discountRate = discountRate;
31    }
32
33    @Override
34    public double applyPromotion(double price) {
35        return price * (1 - discountRate);
36    }
37}
38
39// 上下文:订单处理器
40public class OrderProcessor {
41    private PromotionStrategy strategy;
42
43    public OrderProcessor(PromotionStrategy strategy) {
44        this.strategy = strategy;
45    }
46
47    public double processOrder(double price) {
48        return strategy.applyPromotion(price);
49    }
50}
51
52// 客户端代码
53public class Client {
54    public static void main(String[] args) {
55        OrderProcessor processor = new OrderProcessor(new CashBackPromotion(100, 20));
56        System.out.println(processor.processOrder(150)); // 输出:130.0
57        
58        processor = new OrderProcessor(new DiscountPromotion(0.1));
59        System.out.println(processor.processOrder(100)); // 输出:90.0
60    }
61}
结论

策略模式通过将算法封装在独立的策略类中,实现了算法的解耦和动态选择。它提高了代码的灵活性和可维护性,特别是在需要频繁切换或扩展算法的场景中。通过上述实例,我们可以看到策略模式在不同领域中的实际应用,以及它如何简化复杂系统的管理和升级。

相关推荐
不爱编程的小九九2 小时前
小九源码-springboot097-java付费自习室管理系统
java·开发语言·spring boot
独自破碎E3 小时前
LeetCode 381: O(1) 时间插入、删除和获取随机元素 - 允许重复
java·算法·leetcode
程语有云3 小时前
生产事故-Caffeine缓存误用之临下班的救赎
java·缓存·caffeine·阻塞·log·生产事故
Miraitowa_cheems3 小时前
LeetCode算法日记 - Day 81: 最大子数组和
java·数据结构·算法·leetcode·决策树·职场和发展·深度优先
CodeCraft Studio3 小时前
国产化Word处理控件Spire.Doc教程:用Java实现TXT文本与Word互转的完整教程
java·c#·word·spire.doc·word文档转换·txt转word·word转txt
徐子童3 小时前
数据结构---优先级队列(堆)
java·数据结构·面试题·优先级队列··topk问题
滑水滑成滑头3 小时前
**标题:发散创新:智能交通系统的深度探究与实现**摘要:本文将详细
java·人工智能·python
siriuuus3 小时前
Maven 核心概念及生命周期
java·maven
闭着眼睛学算法4 小时前
【双机位A卷】华为OD笔试之【哈希表】双机位A-跳房子I【Py/Java/C++/C/JS/Go六种语言】【欧弟算法】全网注释最详细分类最全的华子OD真题题解
java·c语言·c++·python·算法·华为od·散列表
孔明兴汉4 小时前
Cursor MCP 第一章-第一节-MCP协议简介.md
java·ai