admin 管理员组

文章数量: 1184232

🧠 一、策略模式简介(什么是 Strategy Pattern)

✅ 定义:

策略模式(Strategy Pattern) 是一种行为型设计模式,它定义了一系列算法(或行为),将每个算法封装成独立的类,并使它们可以互相替换。


✅ 主要解决的问题:

当你有 多个业务算法多个处理方式 时,不希望通过 if-elseswitch-case 来硬编码判断逻辑,而是将不同处理逻辑抽象为策略类,统一调度接口。


✅ 结构图如下:

        +--------------------+           +---------------------+
        |     Context        | --------> |    Strategy(接口) |
        |(上下文,使用策略)|           +---------------------+
        +--------------------+                     ▲
                   |                               |
                   |     +-----------------+       |
                   |     |  StrategyA      | <-----+
                   |     |(具体策略类)    |
                   |     +-----------------+
                   |
                   |     +-----------------+
                   |----> |  StrategyB      |
                         |(具体策略类)    |
                         +-----------------+

🎯 二、适用场景

  • 多种处理逻辑/算法需要自由切换(如推荐算法、加密算法、支付方式)

  • 想避免 if-else 逻辑满天飞

  • 程序需要根据不同上下文执行不同策略


✅ 三、Java 案例讲解(实际策略模式代码)

🌟 案例场景:用户导出数据,有三种格式:CSV、PDF、Excel


第一步:定义策略接口

public interface ExportStrategy {
    void exportData(List<String> data);
}

第二步:实现不同策略类

public class CsvExportStrategy implements ExportStrategy {
    @Override
    public void exportData(List<String> data) {
        System.out.println("导出为 CSV 文件:" + data);
    }
}
​
public class PdfExportStrategy implements ExportStrategy {
    @Override
    public void exportData(List<String> data) {
        System.out.println("导出为 PDF 文件:" + data);
    }
}
​
public class ExcelExportStrategy implements ExportStrategy {
    @Override
    public void exportData(List<String> data) {
        System.out.println("导出为 Excel 文件:" + data);
    }
}

第三步:上下文类(使用策略)

public class ExportContext {
    private ExportStrategy strategy;
​
    public ExportContext(ExportStrategy strategy) {
        this.strategy = strategy;
    }
​
    public void setStrategy(ExportStrategy strategy) {
        this.strategy = strategy;
    }
​
    public void export(List<String> data) {
        strategy.exportData(data);
    }
}

第四步:客户端调用

public class StrategyTest {
    public static void main(String[] args) {
        List<String> data = Arrays.asList("张三", "李四", "王五");
​
        ExportContext context = new ExportContext(new CsvExportStrategy());
        context.export(data); // 输出 CSV
​
        context.setStrategy(new PdfExportStrategy());
        context.export(data); // 输出 PDF
​
        context.setStrategy(new ExcelExportStrategy());
        context.export(data); // 输出 Excel
    }
}

✅ 输出结果:

导出为 CSV 文件:[张三, 李四, 王五]
导出为 PDF 文件:[张三, 李四, 王五]
导出为 Excel 文件:[张三, 李四, 王五]

🧩 四、结合 Spring 的策略模式(自动注入 + Map 注册)

比如你有很多业务节点(如 nodeCode),可以通过 @Component + Map<String, Strategy> 自动注册策略类(你已经在用这种方式了):

@Component
public class StrategyFactory {
    @Autowired
    private Map<String, ExportStrategy> strategyMap;
​
    public ExportStrategy getStrategy(String type) {
        ExportStrategy strategy = strategyMap.get(type);
        if (strategy == null) {
            throw new RuntimeException("未知导出类型: " + type);
        }
        return strategy;
    }
}

只要你策略类写了:

@Component("pdf")
public class PdfExportStrategy implements ExportStrategy { ... }
​
@Component("csv")
public class CsvExportStrategy implements ExportStrategy { ... }

然后你就可以这样用:

ExportStrategy strategy = strategyFactory.getStrategy("csv");
strategy.exportData(data);

✅ 五、总结一句话

策略模式本质上是:将变化的算法封装起来,并通过统一接口调用,消除 if-else 和硬编码,提高扩展性和可维护性。

本文标签: Strategy Pattern