Spring项目中策略模式实现方案

0 本文主要涉及

在基于 Spring 的项目中通过 SpringBean 很方便地实现策略模式方案的介绍说明

1 策略模式简介

设计模式系列中分类为行为型模式的一种,通过把不同处理逻辑封装为策略对象,然后在代码逻辑中通过 context 上下文对象来选择合适的策略对象处理事物
策略模式常用来替代代码中的 if-else 分支逻辑,不过并非代码中有多重 if-else 就需要用策略模式进行重构,只有当这些分支逻辑会经常需要扩展新的分支逻辑场景时才适合使用策略模式,在策略模式下只需增加新的策略对象而不需要修改原来的 if-else 分支处理逻辑,即符合开闭原则(对扩展开放,对修改关闭),这是策略模式的本质作用

2 实现方案简介

在 Spring 项目中可以是通过 SpringBean 自动注入的功能可以很方便 context 上下文对象获取到所有策略对象,再将这些策略对象通过 key-value 方式保存到 static 静态的 map 对象中,就可以实现通过静态方法获取策略对象了(或者不暴露策略对象只提供策略方法);
将根据 key 决定使用哪个策略的逻辑分散到具体策略对象中定义并配合 Map 方法来避免在 context 中维护映射逻辑(网上有些方案示例只是把判断的逻辑挪到 context 中其实并没有做到符合开闭原则)
可以说是 Spring 项目中策略模式最佳实践了

3 代码示例

Context 类定义

/**
 * 策略模式环境上下文
 * 加载已有策略 提供获取策略对象方法
 *
 * @author zhangbohun
 * Create Date 2022/07/09 13:29
 * Modify Date 2022/07/09 13:29
 */
@Component
public class ExampleStrategyContext{
    /**
     * 通过Spring自动注入功能获取到所有实现ExampleStrategyService接口的Bean对象
     */
    @Autowired
    private List exampleStrategyServiceList;
    private static Map strategyServiceMap;

    @PostConstruct
    private void initStrategyServiceMap(){
        strategyServiceMap = exampleStrategyServiceList.stream()
                .collect(Collectors.toMap(ExampleStrategyService::getStrategyKey, Function.identity()));
    }

    /**
     * 静态方法方便非SpringBean对象方法中调用
     * @param type
     * @return
     */
    public static ExampleStrategyService getStrategyService(@NotNull Integer type){
        return strategyServiceMap.get(type);
    }

    /**
     * 调用具体策略业务逻辑方法
     */
    public static void doSomething(@NotNull Integer type){
        return getStrategyService(type).doSomething();
    }
}

策略接口类示例

public interface ExampleStrategyService{
    /**
     * 获取当前策略模式key,一般是被处理数据的类型编码
     * @return
     */
    Integer getStrategyKey();

    /**
     * 代表具体业务逻辑方法
     */
    void doSomething();
}

具体实现策略接口的多个策略类以及通过 Context 类 getStrategyService 方法调用策略处理的逻辑就不赘述了

你可能感兴趣的:(JavaWeb,spring,后端,java,策略模式)