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

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

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}
结论

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

相关推荐
我真会写代码23 分钟前
深度解析并发编程锁升级:从偏向锁到重量级锁,底层原理+面试考点全拆解
java·并发编程·
Meepo_haha29 分钟前
创建Spring Initializr项目
java·后端·spring
会编程的土豆29 分钟前
C++中的 lower_bound 和 upper_bound:一篇讲清楚
java·数据结构·算法
Memory_荒年30 分钟前
SpringBoot事务源码深度游:从注解到数据库的“奇幻漂流”
java·后端·spring
编码忘我33 分钟前
为什么要用SpringBoot
java·后端
神舟之光35 分钟前
Java面向对象编程知识补充学习-2026.3.21
java·开发语言·学习
Memory_荒年42 分钟前
SpringBoot事务:从“一键开关”到“踩坑大全”的生存指南
java·后端·spring
DJ斯特拉1 小时前
SpringAOP
java
张涛酱1074561 小时前
Spring AI 2.0.0-M3 新特性解析:MCP核心集成与重大升级
java
小刘不想改BUG1 小时前
LeetCode 138.随机链表的复制 Java
java·leetcode·链表·hash table