• 浅谈JAVA函数式接口


    什么是函数式接口

    定义: 有且仅有一个抽象方法的接口

    java中有那些函数式接口

    四大内置的函数式接口
    Consumer,Supply,Funcation,Predicate
    其后面会衍生出其他的函数式接口
    具体可参考JDK中的java.util.function包

    如何自定义函数式接口

    1.继承一个函数式接口
    2.将接口上加上@FuncationInterface

    示例:

    /**
     * 报表编排
     *
     * @author Yangqi.Pang
     */
    @FunctionalInterface
    public interface ReportPipeline extends Consumer<ReportPipeline.ReportContext> {
    
        @Data
        @Builder
        @NoArgsConstructor
        @AllArgsConstructor
        class ReportContext {
            /**
             * 报表模板
             */
            private ReportTemplate reportTemplate;
    
            /**
             * 报表请求参数
             */
            private JSONObject reportReq;
    
            /**
             * 模板Id
             */
            private Long templateId;
    
            /**
             * 查询参数Map
             */
            private Map<String, Object> fieldMap;
    
            /**
             * 返回结果
             */
            private List<JSONObject> pageResults;
    
            /**
             * 查询类型
             */
            private QueryType queryType;
    
            /**
             * 参数校验
             */
            public void validate() {
                ExceptionUtil.validate(Objects.nonNull(templateId), "模板Id不能为空");
                ExceptionUtil.validate(Objects.nonNull(reportReq), "传参不能为空");
                ExceptionUtil.validate(Objects.nonNull(queryType), "查询类型不能为空");
            }
    
            @Getter
            @AllArgsConstructor
            public enum QueryType {
                /**
                 * 分页查询
                 */
                PAGE,
                /**
                 * Excel导出
                 */
                EXCEL_EXPORT
            }
        }
    }
    

    对函数式接口的理解

    1.如果我们定义这个类只能做一件事情的时候,我们就可以使用函数式接口,这个就是用来限定这个类的
    2.与接口的不同之处就是,接口可以用来做多个事情,没有限制
    3.函数式接口独特之处,是要把行为也抽象为一个对象

    示例:我们就只定义这个类只能做这一件事情

    /**
     * 分页查询
     *
     * @author Yangqi.Pang
     */
    @Slf4j
    @Component
    public class PageQueryPipeline implements ReportPipeline {
    
        @Resource
        private ReportMapper reportMapper;
    
        @Override
        public void accept(ReportPipeline.ReportContext reportContext) {
            ReportTemplate reportTemplate = reportContext.getReportTemplate();
            List<JSONObject> results = reportMapper.query(reportTemplate.getSql(), reportContext.getFieldMap());
            reportContext.setPageResults(results);
        }
    }
    
  • 相关阅读:
    在Rancher中添加为中国区优化的k8s应用商店的步骤和方法
    debian源配置实例
    面向对象(六)——元类
    异常处理
    面向对象(五)——isinstance与issubclass、反射、内置方法
    面向对象(四)——classmethod、staticmethod装饰器(绑定方法与非绑定方法)
    面向对象(三)——组合、多态、封装、property装饰器
    面向对象(二)——继承
    面向对象(一)——类与对象介绍
    ATM+购物车结构
  • 原文地址:https://www.cnblogs.com/pangyangqi/p/16180077.html
Copyright © 2020-2023  润新知