轻量级策略模式的使用

169 阅读2分钟

轻量级策略模式的使用

策略模式大家也应该都写过、见过不少,哪怕没学过策略模式但是有一定 coding 经验的人一定也写过策略模式,比如:

 if (true) {
     // 调用方法1        
 } else {
      // 调用方法2       
 }

其实if else 就是最鼻祖的设计模式

我们的业务代码中,随处可见的策略模式实现套路 方式:一个接口 + 多个实现类即可实现一个策略模式,如果在idea中点 ctrl 进接口方法出现了多个实现时,这里就是使用了策略模式开发代码

多实现的方式,固然优雅,但是略显笨重,因为要增加多个Java类,那么我们这里使用一种更加轻量级的实现方式:使用 Map + 函数式接口实现:

 java.util.function.Function
 ​
 @Service
 @Slf4j
 public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {
     
 ​
     /**
      * 题目标签服务
      */
     @Resource
     private SubjectLabelService subjectLabelService;
 ​
     private final Map<Integer, Function<String, SubjectOptionBO>> functionMap = new HashMap<>();
     
 ​
     @PostConstruct
     public void initFunctionMao() {
         functionMap.put(1, subjectLabelService::radio);
         functionMap.put(2, subjectLabelService::judfe);
     }
 ​
     public SubjectOptionBO process(Integer subjectType) {
         SubjectOptionBO bo = getFunction(subjectType).apply(subjectType);
         //其他操作
         return bo;
     }
 ​
     public Function<Integer, SubjectOptionBO> getFunction(Integer code) {
         return Optional.ofNullable(functionMap.get(code))
                 .orElseThrow(() -> new RuntimeException("不支持的操作场景:" + code));
     }
 }

这段代码很简单,就是将一些函数缓存在本地的键值对中,执行的时候通过对应的场景码去执行对应的函数

函数式接口

 ​
 /**
  * Represents a function that accepts one argument and produces a result.
  *
  * <p>This is a <a href="package-summary.html">functional interface</a>
  * whose functional method is {@link #apply(Object)}.
  *
  * @param <T> the type of the input to the function
  * @param <R> the type of the result of the function
  *
  * @since 1.8
  */
 @FunctionalInterface
 public interface Function<T, R> {

注解

 // @PostConstruct 注解用于标记一个方法,在对象创建后立即执行。它是 Java EE 中的一种标准注解,通常用于在对象初始化之后执行一些初始化操作。
 // @PostConstruct 注解的生效条件是:
 ​
 //该注解所在的类必须由 Spring 管理,即被 Spring 容器扫描并创建为 Bean。
 //Spring 容器必须启用了对 @PostConstruct 注解的支持。

轻量级策略模式适用场景

  • 适用于同一个领域服务内的函数调用,如果具体实现中包含有多个服务领域的调用还是建议使用类级别的策略模式
  • 可以考虑替代一些if else