【Java知识】Java进阶-策略模式实现

策略模式

策略模式(Strategy Pattern)是一种行为设计模式,它定义了一系列算法,并将每一个算法封装起来,使它们可以互换。策略模式使得算法可以独立于使用它的客户端而变化。

主要角色

  1. 策略接口(Strategy):

    • 这是一个抽象类或接口,定义了所有支持的算法的公共接口。
    • 上下文使用这个接口来调用算法。
  2. 具体策略(Concrete Strategy):

    • 实现了策略接口的具体算法。
    • 具体策略类提供了具体的算法实现,并且可以被上下文使用。
  3. 上下文(Context):

    • 持有一个策略接口的引用。
    • 客户端通过上下文来调用算法。上下文在运行时可以动态地改变策略对象,从而改变算法。

示例代码

以下是一个简单的策略模式示例,用于计算不同折扣策略下的价格。

java 复制代码
// 策略接口
interface DiscountStrategy {
    double calculateDiscount(double price);
}

// 具体策略:无折扣
class NoDiscountStrategy implements DiscountStrategy {
    @Override
    public double calculateDiscount(double price) {
        return price;
    }
}

// 具体策略:百分比折扣
class PercentageDiscountStrategy implements DiscountStrategy {
    private double percentage;

    public PercentageDiscountStrategy(double percentage) {
        this.percentage = percentage;
    }

    @Override
    public double calculateDiscount(double price) {
        return price * (1 - percentage / 100);
    }
}

// 具体策略:固定金额折扣
class FixedAmountDiscountStrategy implements DiscountStrategy {
    private double amount;

    public FixedAmountDiscountStrategy(double amount) {
        this.amount = amount;
    }

    @Override
    public double calculateDiscount(double price) {
        return price - amount;
    }
}

// 上下文
class ShoppingCart {
    private DiscountStrategy discountStrategy;

    public ShoppingCart(DiscountStrategy discountStrategy) {
        this.discountStrategy = discountStrategy;
    }

    public void setDiscountStrategy(DiscountStrategy discountStrategy) {
        this.discountStrategy = discountStrategy;
    }

    public double calculateTotal(double price) {
        return discountStrategy.calculateDiscount(price);
    }
}

// 客户端代码
public class StrategyPatternDemo {
    public static void main(String[] args) {
        double price = 100.0;

        ShoppingCart cart = new ShoppingCart(new NoDiscountStrategy());
        System.out.println("Total price with no discount: " + cart.calculateTotal(price));

        cart.setDiscountStrategy(new PercentageDiscountStrategy(10));
        System.out.println("Total price with 10% discount: " + cart.calculateTotal(price));

        cart.setDiscountStrategy(new FixedAmountDiscountStrategy(15));
        System.out.println("Total price with $15 discount: " + cart.calculateTotal(price));
    }
}

优点

  1. 算法自由切换:策略模式使得算法可以独立于使用它的客户端而变化。
  2. 扩展性好:通过增加新的策略类,可以很容易地扩展系统。
  3. 避免多重条件判断:使用策略模式可以避免在客户端代码中使用多重条件判断来选择算法。

缺点

  1. 策略类数量增加:当策略数量较多时,会增加类的数量,从而增加系统的复杂性。
  2. 客户端需要了解策略:客户端需要知道有哪些策略可供选择,并了解如何创建和配置这些策略对象。

适用场景

  • 当有多种算法需要实现,并且这些算法可以互换时。
  • 当算法在运行时需要动态地改变时。
  • 当算法的实现需要隐藏,或者算法的实现细节对客户端不可见时。

策略模式是一种非常灵活的设计模式,适用于需要动态选择算法的场景。通过封装算法,策略模式使得算法的变化不会影响到使用它的客户端代码。

相关文献

【知识科普】一篇文章教你学会设计模式

相关推荐
Java后端的Ai之路2 小时前
RAG 还是 Agent 自主检索?Claude Code 删掉向量库之后,我把选型讲透了
开发语言·人工智能·prompt·agent·rag
starzy19902 小时前
深入理解Scala高阶函数:函数式编程核心
开发语言·scala
2601_962106647 小时前
【Java Set综合实战】商品管理系统 + 图书收藏系统|Product、Book自定义类全套代码
java
RuoyiOffice7 小时前
SpringBoot+Vue3 凭证生命周期设计:审核、过账、冲销与反过账怎样保持账目一致
java·spring boot·事务·springboot3·财务系统·会计凭证·ruoyi office
2601_962106648 小时前
HashMap入门|工号-姓名键值存储、两种遍历方式、根据key/value查
java
czq_26867194878 小时前
Python打卡第46天
开发语言·python
杨凯凡8 小时前
Spring Framework 7 API 版本管理实战:请求头路由、兼容迁移与废弃策略
java·rest api·springframework·spring boot 4·api版本管理
T_Wizard9 小时前
同一个问题写了 4 遍:官方 SDK / HTTP / Spring AI / LangChain4j,到底该选哪个
java·ai编程
hai_android9 小时前
AudioTrack 深度解析:从原理到实战
android·java·kotlin
斯维赤9 小时前
限流、熔断、降级,你真的分得清吗?
java·后端·架构