首页 > 编程语言 >Java 用Lambda实现一个通用的制造者工具

Java 用Lambda实现一个通用的制造者工具

时间:2022-11-22 23:11:31浏览次数:67  
标签:制造者 function predicate code Java after util return Lambda

在我们日常开发中,虽然是用了lombok在实体类中已经帮我们省了get、set方法,但是在公司的项目中,还是经常会出现new一个对象然后一个个的给它set值的情况,太丑了,如下图

List<String> staffList = Arrays.asList(distribute.getStaffIds().split(","));
for(String staffId : staffList) {
    EbCorporateActivityDistributeStaffList distributeStaffList = new EbCorporateActivityDistributeStaffList();
    distributeStaffList.setDistributeId(distribute.getId());
    distributeStaffList.setStaffId(staffId);
    distributeStaffListMapper.insert(distributeStaffList);
}

后来我专门的去网上学习、研究,如何避免这个问题,最后封装了一个工具类,如下

 

 

 

我处于两种原因喜欢这种建造方式
1、提到的setter方法去建造对象,可能需要new先创建出来,然后用一行行代码setXX去完成属性的初始化,我个人是不太喜欢这样的编码风格
2、这个建造者最想表达的是"惰性思想",只有在最后build之后才会拿到构造好的(属性初始化完成的)对象实例,这在高并发环境下是相对安全的,
否则在set过程中,对象实例随时可以被获取的,就会导致没有初始化完成的对象实例提前暴露,
当然你也可以通过别的方式去避免这样的问题,我的这个想法只是其中一种解法
我写的有问题的地方或者你们有更好的方法,欢迎评论,大家互相学习

 

 

 

先来了解一下这些函数式接口

 

JDK提供了大量常用的函数式接口以丰富Lambda的典型使用场景,它们主要在java.util.function 包中被提供。

Supplier接口

java.util.function.Supplier<T> 接口仅包含一个无参的方法: T get() 。用来获取一个泛型参数指定类型的对象数据。由于这是一个函数式接口,这也就意味着对应的Lambda表达式需要“对外提供”一个符合泛型类型的对象数据。

package java.util.function;
 
/**
 * Represents a supplier of results.
 *
 * <p>There is no requirement that a new or distinct result be returned each
 * time the supplier is invoked.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #get()}.
 *
 * @param <T> the type of results supplied by this supplier
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Supplier<T> {
 
    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

 

Consumer接口

 

java.util.function.Consumer<T> 接口则正好与Supplier接口相反,它不是生产一个数据,而是消费一个数据,其数据类型由泛型决定。

package java.util.function;
 
import java.util.Objects;
 
/**
 * Represents an operation that accepts a single input argument and returns no
 * result. Unlike most other functional interfaces, {@code Consumer} is expected
 * to operate via side-effects.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #accept(Object)}.
 *
 * @param <T> the type of the input to the operation
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Consumer<T> {
 
    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
 
    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

 

Predicate接口

有时候我们需要对某种类型的数据进行判断,从而得到一个boolean值结果。这时可以使用java.util.function.Predicate<T> 接口。

package java.util.function;
 
import java.util.Objects;
 
/**
 * Represents a predicate (boolean-valued function) of one argument.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #test(Object)}.
 *
 * @param <T> the type of the input to the predicate
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Predicate<T> {
 
    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
 
    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ANDed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * AND of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }
 
    /**
     * Returns a predicate that represents the logical negation of this
     * predicate.
     *
     * @return a predicate that represents the logical negation of this
     * predicate
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }
 
    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * OR of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code true}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ORed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * OR of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }
 
    /**
     * Returns a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}.
     *
     * @param <T> the type of arguments to the predicate
     * @param targetRef the object reference with which to compare for equality,
     *               which may be {@code null}
     * @return a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

 

Function接口

java.util.function.Function<T,R> 接口用来根据一个类型的数据得到另一个类型的数据,前者称为前置条件,后者称为后置条件。

package java.util.function;
 
import java.util.Objects;
 
/**
 * 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> {
 
    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
 
    /**
     * Returns a composed function that first applies the {@code before}
     * function to its input, and then applies this function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of input to the {@code before} function, and to the
     *           composed function
     * @param before the function to apply before this function is applied
     * @return a composed function that first applies the {@code before}
     * function and then applies this function
     * @throws NullPointerException if before is null
     *
     * @see #andThen(Function)
     */
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }
 
    /**
     * Returns a composed function that first applies this function to
     * its input, and then applies the {@code after} function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of output of the {@code after} function, and of the
     *           composed function
     * @param after the function to apply after this function is applied
     * @return a composed function that first applies this function and then
     * applies the {@code after} function
     * @throws NullPointerException if after is null
     *
     * @see #compose(Function)
     */
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }
 
    /**
     * Returns a function that always returns its input argument.
     *
     * @param <T> the type of the input and output objects to the function
     * @return a function that always returns its input argument
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

 

学完了这些后,我做了个通用的建造者工具类,代码如下

package com.tring.ysyn.util;


import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @author Tring
 * date 2022-11-22
 */
public class Builder<T> {

    /**
     * 存储调用方 指定构造类的 构造器
     */
    private final Supplier<T> constructor;

    /**
     * 存储 指定类 所有需要初始化的属性
     */
    private final List<Consumer> dInject = new ArrayList<>();

    private Builder(Supplier<T> constructor){
        this.constructor = constructor;
    }

    public static <T> Builder<T> builder(Supplier<T> constructor){
        return new Builder<>(constructor);
    }

    public <P1> Builder<T> with(Builder.DinjectConsumer<T,P1> consumer,P1 p1){
        Consumer<T> c = instance ->consumer.accept(instance,p1);
        dInject.add(c);
        return this;
    }



    public T build(){
        //调用supplier 生成类示例
        T instance = constructor.get();
        //调用传入的setter方法,完成属性的初始化
        dInject.forEach(dInject -> dInject.accept(instance));
        //返回构造完成的类实例
        return instance;
    }

    @FunctionalInterface
    public interface DinjectConsumer<T,P1>{
        void accept(T t,P1 p1);
    }
}

 

 

测试类

package com.tring.ysyn.util;

import com.tring.ysyn.entity.SysUser;

/**
 * @author Tring
 * date 2022-11-22
 */
public class Test {

    public static void main(String[] args) {
        //测试
        SysUser user = Builder.builder(SysUser::new).with(SysUser::setNickName,"张三").with(SysUser::setPhone,"13222222222").build();
        System.out.println(user);
    }
}

 

效果图

 

标签:制造者,function,predicate,code,Java,after,util,return,Lambda
From: https://www.cnblogs.com/LarryBlogger/p/16916848.html

相关文章

  • javaSE基础-数组
    数组数组的简述1、数组:是多个相同类型数据一定顺序排列的集合,并使用一个名字命名,并通过编号的方式对这些数据进行同一管理2、数组的相关概念:数组名元素角标、下标、......
  • JAVA- 动漫美女拼图(给按钮添加事件)
    代码一packagecom.itheima_05;publicclassApp{publicstaticvoidmain(String[]args){PictureFramepf=newPictureFrame();}}代码二pa......
  • JAVA- 动漫美女拼图(记录0号图片位置)
    代码一packagecom.itheima_02;publicclassApp{publicstaticvoidmain(String[]args){PictureFramepf=newPictureFrame();}}代码二pa......
  • Java多线程 线程池的生命周期及运行状态
    (目录)一、说明线程池的生命周期线程池的状态runState和工作线程数量workerCount共同保存在AtomicInteger类型的控制变量ctl中ctl高三位保存运行状态(2^3^=8>5),低2......
  • java爬虫
    创建Maven工程加入依赖<!--https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient--><dependency><groupId>org.apache.httpcomponents</gr......
  • 【JAVA笔记】jJAVA入门基础02
     一.符号及类型1.1添加注释comment注释:就是对代码的解释和说明。其目的是让人们能够更加轻松地了解代码。为代码添加注释,是十分必须要的,它不影响程序的编译和运行......
  • Java基础题
    Java基础题1.Java面向对象有哪些特征继承、封装、多态三大特征相互相乘封装:封装内部的一些实现机制,就跟方法封装一些实现的机制一样继承:就是从已有的类派生出新的类,新......
  • Java基础
    java基础一.java注释1.单行注释:////这是单行注释2.多行注释:/*注释内容*//*这是多行注释这是多行注释*/3.文档注释(JavaDoc):/**注释内容*//***@......
  • java变量 运算符包机制 doc
    java基础2一.变量java变量是程序中最基本存储单元,要素包含变量名变量类型作用域数据类型变量类型变量名=值;例:Stringa='shiftnm';变量作用域类......
  • javascript-代码随想录训练营day7
    454.四数相加Ⅱ题目链接:https://leetcode.cn/problems/4sum-ii/题目描述:给你四个整数数组nums1、nums2、nums3和nums4,数组长度都是n,请你计算有多少个元组(i,j,......