• 设计模式在参数校验中的使用


    设计模式在参数校验中的使用

    设计模式在我们项目代码中无处不在,但是我们知道这些设计模式的名词,但是使用它们确实异常地困难,下面参考一位大佬的博客,下面是他的博客地址,从一个特定的需求场景出发,谈谈设计模式应该如何在该场景下使用??
    大佬的博客链接

    需求:

    我们对于动态数据库表的校验,例如它新建时一些字段的非空校验;编辑时一些字段是否可编辑校验;一些字段的类型校验等等…此时,我们针对不同情况需要进行不同校验规则的校验,有的时候可能还需要多重校验叠加等情况,在这种背景下,使用设计模式进行业务拆解设计能够起到很大的作用和效果
    以上需求可以大致如下图所示:
    在这里插入图片描述
    首先,我们对于校验来说,肯定不能叫繁重的校验代码在我们的Controoler层或者Service层进行编写,这样极大地增加了代码的繁重性和冗余,首先想到的就是利用代理帮我们进行校验,即通过注解+Aop切面类进行校验处理:

    注解类:ParamCheck

    @Target(ElementType.METHOD)   //作用在方法上
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface ParamCheck {
    
        /**
         * 参数为枚举数组类型:因为校验规则可能是一些、多个规则的叠加
         * @return
         */
        FieldCheckEum[] value() default {};
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    枚举类:FieldCheckEum

    @Getter
    @AllArgsConstructor
    public enum FieldCheckEum {
    
        CHECK_FIELD_EXIST(0,"存在校验"),
    
        CHECK_FILED_NULL(1,"非空校验"),
    
        CHECK_FILED_SEARCH(2,"搜索校验"),
    
        CHECK_FILED_EDIT(3,"编辑校验"),
    
        CHECK_FILED_IMPORT(4,"导入校验"),
    
        CHECK_FILED_SORT(5,"排序校验"),
    
        CHECK_FILED_TYPE(6,"类型校验");
    
        private Integer code;
        private String value;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    切面类:ParamCheckAspect

    @Aspect
    @Component
    @Slf4j
    public class ParamCheckAspect {
    
        @Pointcut("@annotation(com.feng.study.go_api.else_if.ParamCheck)")
        public void paramCheck() {
    
        }
    
        @Before("paramCheck()")
        public void doBefore(JoinPoint joinPoint) {
            //通过切点获取注解中的方法签名
            MethodSignature signature = (MethodSignature)joinPoint.getSignature();
            //获取注解中的方法
            Method method = signature.getMethod();
            Method targetMethod = AopUtils.getMostSpecificMethod(method, joinPoint.getTarget().getClass());
            //再获取被注解的类携带的参数
            Object[] args = joinPoint.getArgs();
            if (null == args || args.length <= 0) {
                //异常处理
            }
            //获取当前方法注解中的参数
            ParamCheck paramCheck = AnnotationUtils.findAnnotation(targetMethod, ParamCheck.class);
            //获取注解
            Map<String, Object> argument = (Map<String, Object>) args[0];
            //获取表结构集合
            List<TableModel> tableModels = new ArrayList<>();
            //构建校验参数
            ParamCheckDto build = ParamCheckDto.builder()
                    .argument(argument)
                    .tableModels(tableModels)
                    .checkEnums(Arrays.asList(paramCheck.value()))
                    .build();
            //利用工厂执行校验责任链
            FiledCheckHandlerFactory.processHandler(build);
        }    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    观察切面类,首先我们看到最后一行代码:

    //利用工厂执行校验责任链
    FiledCheckHandlerFactory.processHandler(build);
    
    • 1
    • 2

    使用工厂进行参数的校验,那么工厂如何进行初始化呢??

    工厂类:FiledCheckHandlerFactory

    @Component
    public class FiledCheckHandlerFactory implements CommandLineRunner, ApplicationContextAware {
        /**
         * 1. CommandLineRunner:接口主要用于应用初始化,初始化代码在应用生命周期中只执行一次
         * 2. AnnotationAwareOrderComparator:继承OrderComparator,责任链中的每一个Handler具有注解(@Order(n)),
         * 通过@Order注解,然后通过Collections.sort(list, AnnotationAwareOrderComparator.INSTANCE)可对Handler进行对应排序
         *
         */
        private volatile ApplicationContext applicationContext;
        private static FieldCheckHandler handlers;
    
        /**
         * 拼接各种责任链
         * @param args
         * @throws Exception
         */
        @Override
        public void run(String... args) throws Exception {
            //获取所有校验Handler的Bean对象,进行责任链的拼接
            Collection<FieldCheckHandler> checkHandlers = this.applicationContext.getBeansOfType(FieldCheckHandler.class).values();
            ArrayList<FieldCheckHandler> list = Lists.newArrayList(checkHandlers);
            Collections.sort(list, AnnotationAwareOrderComparator.INSTANCE);
            /**
             * 此处是假设的链式拼接方式,实际开发中责任链依据实际需求而定
             */
            for (int i = 0; i < list.size() - 1; i++) {
                list.get(i).setNextHandler(list.get(i + 1));
            }
            handlers = list.get(0);
        }
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = applicationContext;
        }
    
    
        /**
         * 使用责任链处理器进行对应参数的校验处理    委托模式
         * @param paramCheckDto
         */
        public static void processHandler(ParamCheckDto paramCheckDto) {
            handlers.handler(paramCheckDto);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    在工厂类中我们合理利用Spring容器给我们的钩子,使用applicationContext进行初始化工作,将参数校验的处理器构建责任链,并利用责任链处理器进行参数的统一校验工作。那这些责任链模式的处理器又是如何定义的呢?

    抽象责任链处理器类:FieldCheckHandler

    其中:

    • **getType()**获取该处理器校验的规则类型
    • handler()方法进行实际的校验逻辑,抽象责任链处理器作为父类,调用该方法会去对应子类的handler方法,这就是所谓的模版方法模式
    @Data
    public abstract class FieldCheckHandler {
    
        protected FieldCheckHandler nextHandler = null;
    
        public abstract FieldCheckEum getType();
    
        public void handler(ParamCheckDto paramCheckDto) {
            if (paramCheckDto.getCheckEnums().contains(getType())) {
                checkHandler(paramCheckDto);
            }
            if (null == nextHandler) {
                return;
            }
            nextHandler.handler(paramCheckDto);
        }
    
        /**
         * 子类具体校验
         *
         * @param paramCheckDto
         */
        public abstract void checkHandler(ParamCheckDto paramCheckDto);
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    除此之外,对应参数校验,一般从注解中获取对应的方法和校验类型数组后,将其封装成对应的校验参数Dto,责任链处理器拿到对应的校验参数Dto进行具体类型的校验判断。

    参数校验Dto:ParamcheckDto

    @AllArgsConstructor
    @Data
    @Builder
    public class ParamCheckDto {
        /**
         * 方法
         */
        Map<String, Object> argument;
    
        /**
         * 表结构集合
         */
        List<TableModel> tableModels;
    
        /**
         * 校验参数集合,即枚举的value集合
         */
        List<FieldCheckEum> checkEnums;
    
        /**
         * 表名
         */
        String tableName;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    最后整体的设计结构如下图所示:
    在这里插入图片描述

  • 相关阅读:
    nodejs(一)fs模块(操作文件的模块),path路径模块,路径拼接path.join,抵消两层路径的写法,浏览器中的js
    http2 wireshark未解码消息字段过滤
    各种LLM数据集包括SFT数据集
    Vue进阶之Vue无代码可视化项目(一)
    c语言练习6
    Java集合实例
    【笔者感悟】笔者的工作感悟【四】
    【Linux kernel/cpufreq】framework ----big Little driver
    测试用例的8大设计原则
    lamp搭建
  • 原文地址:https://blog.csdn.net/SmallPig_Code/article/details/126413199