springboot项目实现策略模式,优雅的整活

  1. 众所周知,项目中的业务处理可能一条线会有多种实现,例如一个下单就可能根据商品类型有多种处理的逻辑,此时,如果使用策略模式那么对该功能的拓展性、可读性都有明显的增强。
  2. 虽然说 if-else也可以实现策略模式,一人一个想法,策略模式也有无数的实现方式,本人自开发以来也写了很多套策略模式的实现,这次又写了一套自认优雅与拓展都很全面的方式去实现,各位看官请往下看。
  3. 首先定义自定义策略注解,再定义一个策略接口的(将需要实现的策略抽象在接口里),利用spring提供的IOC,将策略都注册到容器中,再首次调用策略时将所有的策略按照自定义注解的值存到对应的Map容器中,在业务方根据策略key获取实际的策略实现类调用方法。
  4. 以下是代码,首先定义一个策略模式处理handler,通用的,将所有策略模式需要用到的方法封装,减少调用方的编码。
  5. 核心base handler代码:使用了模板模式,直接调用抽象方法把具体实现交给子类,因为实际调用方是子类。
package com.central.common.handler;

import cn.hutool.core.map.MapUtil;
import com.central.common.utils.Assert;
import org.springframework.context.ApplicationContext;

import java.lang.annotation.Annotation;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 处理策略的 处理工具的基本类
 *
 * @Date 2023/3/8 17:59
 */
public abstract class BaseStrategyHandler<T, R extends Annotation> {

    protected ApplicationContext applicationContext;

    public BaseStrategyHandler(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * 容器
     */
    protected ConcurrentHashMap<String, Class<T>> container = new ConcurrentHashMap();

    /**
     * 返回指定的策略枚举
     */
    protected abstract Class<R> getStrategyAnnotationClass();

    /**
     * 返回指定的策略 接口类
     */
    protected abstract Class<T> getStrategyInterface();

    /**
     * 获取 注解的值
     * 为了处理可能枚举值是数组的情况,因此需要包装成集合
     * 为了避免多个策略键用的同一个策略实现的情况
     * @date 17:41 2023/7/6
     * @param strategyAnnotationEntity 注解实体
     * @return java.util.List<java.lang.String>
     **/
    protected abstract List<String> getStrategyAnnotationValue(R strategyAnnotationEntity);

    /**
     * 根据class 获取Bean
     *
     * @param clazz
     * @return T
     * @date 17:06 2023/3/9
     **/
    protected T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 获取类上的 枚举实体
     * @date 17:44 2023/7/6
     * @param service 策略类实体
     * @return R 枚举实体
     **/
    protected R getStrategyAnnotationEntity(Class<T> service) {
        Class<R> strategyAnnotationClass = this.getStrategyAnnotationClass();
        boolean annotationPresent = service.isAnnotationPresent(strategyAnnotationClass);
        Assert.isTrue(!annotationPresent, "策略实现存在未加注解的异常");
        return service.getAnnotation(strategyAnnotationClass);
    }

    /**
     * 懒加载的方式 初始化容器
     * @date 17:50 2023/7/6
     * @param
     * @return void
     **/
    protected void lazyInitContainer(){

        ConcurrentHashMap<String, Class<T>> container = this.container;
        // 获取策略接口
        Class<T> strategyInterface = this.getStrategyInterface();
        // 获取所有 实现类的spring bean
        applicationContext.getBeansOfType(strategyInterface).forEach((k, v) -> {
            Class<T> service = (Class<T>) v.getClass();
            // 获取策略实体上的枚举实体
            R strategyAnnotationEntity = this.getStrategyAnnotationEntity(service);
            // 获取枚举上的值
            List<String> strategyAnnotationValue = this.getStrategyAnnotationValue(strategyAnnotationEntity);
            // 置入策略容器
            strategyAnnotationValue.stream().forEach(value -> container.putIfAbsent(value, service));
        });
    }

    /**
     * 获取策略实体 供外部调用的
     * @date 17:44 2023/7/6
     * @param strategyKey
     * @return java.lang.Class<T>
     **/
    public T getStrategyEntity(String strategyKey) {
        // 获取容器
        ConcurrentHashMap<String, Class<T>> container = this.container;
        if (MapUtil.isEmpty(container)) {
            this.lazyInitContainer();
        }
        return this.getBean(container.get(strategyKey));
    }
}

  1. 子类handler代码:
package com.central.keep.strategy.orderRegRelation;

import com.central.common.dto.saveDto.OrderRegRelationSaveDto;
import com.central.common.enums.CommonEnum;
import com.central.common.handler.BaseStrategyHandler;
import com.central.common.utils.Assert;
import com.central.keep.annotation.OrderRegRelationAnnotation;
import com.central.keep.model.OrderRegRelation;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * OrderRegRelationStrategyHandler
 * @Date 2023/7/12 17:07 
 * @Description 
 */ 
@Component
public class OrderRegRelationStrategyHandler extends BaseStrategyHandler<OrderRegRelationStrategy, OrderRegRelationAnnotation> {

  	/**
     * 初始化,提供spring的ApplicationContext  spring在初始化bean时会将ApplicationContext 
     **/
    public OrderRegRelationStrategyHandler(ApplicationContext applicationContext) {
        super(applicationContext);
    }

	// 提供自定义注解类
    @Override
    protected Class<OrderRegRelationAnnotation> getStrategyAnnotationClass() {
        return OrderRegRelationAnnotation.class;
    }

	// 提供 策略接口类
    @Override
    protected Class<OrderRegRelationStrategy> getStrategyInterface() {
        return OrderRegRelationStrategy.class;
    }

    @Override
    protected List<String> getStrategyAnnotationValue(OrderRegRelationAnnotation strategyAnnotationEntity) {
        return Collections.singletonList(strategyAnnotationEntity.value().getCode());
    }

    /**
     * 策略 handler 提供整体的逻辑处理,也可以写在 对应的 service层中
     * @date 17:44 2023/7/12
     * @param orderRegRelationSaveDto
     * @return com.central.keep.model.OrderRegRelation
     **/
    public OrderRegRelation buildOrderRegRelation(OrderRegRelationSaveDto orderRegRelationSaveDto){
        // 获取策略类
        OrderRegRelationStrategy strategyEntity = this.getStrategyEntity(orderRegRelationSaveDto.getBizType());
        Assert.isObjEmpty(strategyEntity, CommonEnum.ExceptionDesc.参数异常);
        // 策略实现类调用 实现的策略方法
        OrderRegRelation orderRegRelation = strategyEntity.setEntityAttributes(orderRegRelationSaveDto);
        return orderRegRelation;
    }
}

  1. 自定义注解代码:
package com.central.keep.annotation;

import com.central.common.enums.BizEnum;

import java.lang.annotation.*;

/**
 * OrderRegRelationAnnotation
 * keep 订单reg 的枚举
 *
 * @author chenkaimin
 * @Date 2023/7/12 17:05
 * @Description
 * @see com.central.common.enums.BizEnum.BizTypeEnum
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OrderRegRelationAnnotation {

    BizEnum.BizTypeEnum value();
}

public class BizEnum {
	/**
     * BizTypeEnum
     * 业务商品表类型 枚举
     *
     * @author chenkaimin
     * @Date 2023/7/3 14:59
     * @Description
     */
    @Getter
    @AllArgsConstructor
    public enum BizTypeEnum {
        Keep_Curriculum("keep_curriculum", "keep 课程"),
        Keep_Activity("keep_activity", "keep 活动"),
        ;
        String code;
        String desc;
    }
}
  1. 策略接口类:
package com.central.keep.strategy.orderRegRelation;

import com.central.common.dto.saveDto.OrderRegRelationSaveDto;
import com.central.keep.model.OrderRegRelation;

/**
 * OrderRegRelationStrategy
 * 订单reg 策略
 *
 * @Date 2023/7/12 17:19
 * @Description
 */
public interface OrderRegRelationStrategy {

    /**
     * 订单reg 实体需要的业务的实体的字段置入
     * @date 17:43 2023/7/12
     * @param orderRegRelationSaveDto
     * @return com.central.keep.model.OrderRegRelation
     **/
    OrderRegRelation setEntityAttributes(OrderRegRelationSaveDto orderRegRelationSaveDto);
}

  1. 调用方代码例子:
public Boolean saveOrderRegRelation(OrderRegRelationSaveDto orderRegRelationSaveDto){
        OrderRegRelation orderRegRelation = orderRegRelationStrategyHandler.buildOrderRegRelation(orderRegRelationSaveDto);
        return this.save(orderRegRelation);
    }
  1. 核心是BaseStrategyHandler ,分为容器(Map<策略值,策略实现>)、枚举(策略键定义)、接口(策略抽象与实现) ,配合spring的IOC就构成了这套策略模式的实现。拓展只需要多一个策略接口的实现即可。如果有多套策略需要实现,每套策略需要编写一个类似OrderRegRelationStrategyHandler 的子类。个人感觉整体逻辑会更清晰,可以作为一个项目的全局策略实现的底层来使用。
  2. 结尾附上完整的流程图,更容易理解一点,感谢网友给出意见。
    在这里插入图片描述
  3. 这个说白了核心思想就是在注解里定义key值,然后按照key,value的结构把key值和对应的策略实现类放到ConcurrentHashMap里面。然后调用策略的时候根据你的不同的key值使用子类调用 BaseStrategyHandler#getStrategyEntity()的方法获取策略,然后直接用具体的策略实现类去调用你的不同的策略。

留言:老婆做了一个小红书账号,全是瓷砖方面的干货,大佬们如果有需求或者有兴趣可以移步了解一下,嘻嘻~

小红书地址,GO GO GO!!!
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值