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

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

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

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

相关推荐
yaoxin5211234 分钟前
381. Java IO API - 控制文件树遍历流程
java·开发语言
SimonKing5 分钟前
OpenCode 20 个斜杠命令,90% 的人只用过 3 个
java·后端·程序员
尽兴-6 分钟前
Spring与Dubbo整合原理与源码分析
java·spring·dubbo·enabledubbo
Gopher_HBo6 分钟前
BlockingQueue详解
java·后端
白露与泡影6 分钟前
为什么在IDEA使用@Autowired会报黄?
java·ide·intellij-idea
我登哥MVP9 分钟前
【Spring6笔记】 - 15 - Spring中的八大设计模式
java·spring boot·笔记·spring·设计模式·intellij-idea
蚰蜒螟15 分钟前
深入剖析 Tomcat 9.0.53 源码:Web 资源管理与类加载机制
java·前端·tomcat
m0_4750645019 分钟前
Spring AI文档切片
java·人工智能·spring
我登哥MVP19 分钟前
【SpringMVC笔记】 - 1 - SpringMVC入门
java·spring boot·spring·tomcat·maven·intellij-idea·springmvc
Arva .21 分钟前
Spring 事务传播机制 速记
java·数据库·spring