小蔡学Java

Java之设计模式 (八)

2023-09-18 17:56 931 0 设计模式 设计模式策略模式

策略模式(Strategy Pattern)

  Java 策略模式是一种行为型设计模式,它定义了一系列的算法,将每个算法都封装起来,并使它们可以互相替换,从而使算法的变化不会影响到使用算法的客户端。这种模式可以使算法的变化更加灵活和可控,同时也可以提高代码的可读性和可维护性。

使用场景

  • 当一个对象具有多种行为或算法,并且需要在运行时动态选择其中一种时,策略模式可以派上用场。

  • 当需要对同一种行为或算法进行多种实现时,我们可以使用策略模式。

  • 当需要减少大量的 if/else 语句时,我们可以使用策略模式来优化代码。

代码实现

  假设有一个电商网站,它需要根据不同的促销策略来计算订单的价格。促销策略包括打折、满减、直降等等。   首先,我们定义一个促销策略接口,其中包含一个计算订单价格的方法

public interface PromotionStrategy {
    double calculatePrice(double price);
}

  然后,我们实现具体的促销策略,例如打折、满减和直降策略:

public class DiscountPromotionStrategy implements PromotionStrategy {
    private double discount;

    public DiscountPromotionStrategy(double discount) {
        this.discount = discount;
    }

    public double calculatePrice(double price) {
        return price * (1 - discount);
    }
}
public class FullReductionPromotionStrategy implements PromotionStrategy {
    private double threshold;
    private double reduction;

    public FullReductionPromotionStrategy(double threshold, double reduction) {
        this.threshold = threshold;
        this.reduction = reduction;
    }

    public double calculatePrice(double price) {
        return price >= threshold ? price - reduction : price;
    }
}
public class DirectReductionPromotionStrategy implements PromotionStrategy {
    private double reduction;

    public DirectReductionPromotionStrategy(double reduction) {
        this.reduction = reduction;
    }

    public double calculatePrice(double price) {
        return price - reduction;
    }
}

  最后,我们定义一个订单类,其中包含一个 PromotionStrategy 对象和一个 calculatePrice 方法:

public class Order {
    private double price;
    private PromotionStrategy promotionStrategy;

    public Order(double price, PromotionStrategy promotionStrategy) {
        this.price = price;
        this.promotionStrategy = promotionStrategy;
    }

    public double calculatePrice() {
        return promotionStrategy.calculatePrice(price);
    }
}

  创建一个订单,并指定不同的促销策略来计算订单价格:

Order order = new Order(100, new DiscountPromotionStrategy(0.1));
double price = order.calculatePrice(); // 90

order = new Order(200, new FullReductionPromotionStrategy(150, 50));
price = order.calculatePrice(); // 150

order = new Order(300, new DirectReductionPromotionStrategy(50));
price = order.calculatePrice(); // 250

使用小结

策略模式是 Java 中经常使用的一种设计模式,它可以在很多场景中使用,比如:

可以使用策略模式定义多种日志记录方式(例如控制台输出、文件输出、网络传输等)并动态选择使用哪种方式进行日志记录。

可以使用策略模式定义多种支付方式(例如微信支付、支付宝支付、银行卡支付等)并让用户动态选择使用哪种支付方式进行支付。

可以使用策略模式定义多种加密算法(例如对称加密、非对称加密、哈希算法等)并让用户动态选择使用哪种加密算法进行数据加密。

通过使用策略模式,我们可以更灵活地实现不同的功能需求,并让用户根据实际情况选择最合适的策略进行操作

评论( 0 )

  • 博主 Mr Cai
  • 坐标 河南 信阳
  • 标签 Java、SpringBoot、消息中间件、Web、Code爱好者

文章目录