一看就会的java8通用Builder

一、前言

最近回顾了一下java8语法,其中发现了一个很有意思的一对逆运算接口:

  1. Supplier:这个接口是用来创建对象的,最大的特点是懒加载。
  1. Supplier接口源码
@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}
  1. 调用方法
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = false)
public class Sign {
    private String alg;
    private String value;
    private String cert;

    public static void main(String[] args) {
        创建Supplier容器,声明为TestSupplier类型,此时并不会调用对象的构造方法,即不会创建对象
        Supplier<Sign> sign = Sign::new;
        //调用get()方法,此时会调用对象的构造方法,即获得到真正对象
        System.out.println(sign.get());
    }
}

打印结果:Sign(super=com.infosec.ra.entity.Sign@5750a, alg=null, value=null, cert=null)

  1. Consumer:顾名思义,这是一个对象消费者
  1. Consumer接口源码
@FunctionalInterface
public interface Consumer<T> {
    
    //接收一个参数
    void accept(T t);

    //调用者方法执行完后再执行after的方法
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}
  1. 调用方法
import java.util.function.Consumer; 
public class ConsumerTest {    
    public static void main(String[] args) {        
        Consumer<Integer> consumer = (x)->{
            int num = x * 1;
            System.out.println(num);        
        };        
        Consumer<Integer> consumer1 = (x) -> {            
            int num = x * 2;            
            System.out.println(num);        
        };        
        consumer.andThen(consumer1).accept(1);    
    }
}

执行结果为:10 20,说明先执行consumer的方法,然后再执行consumer1的方法。

二、利用Supplier和Consumer构建java8通用Builder

  1. Builder代码示例(本文核心)
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @author Javacfox
 */
public class Builder<T> {

    private final Supplier<T> instantiator;

    private List<Consumer<T>> modifiers = new ArrayList<>();

    public Builder(Supplier<T> instant) {
        this.instantiator = instant;
    }

    public static <T> Builder<T> of(Supplier<T> instant) {
        return new Builder<>(instant);
    }

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

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

    public <P1, P2, P3> Builder<T> with(Consumer3<T, P1, P2, P3> consumer, P1 p1, P2 p2, P3 p3) {
        Consumer<T> c = instance -> consumer.accept(instance, p1, p2, p3);
        modifiers.add(c);
        return this;
    }

    public <P1, P2, P3,P4> Builder<T> with(Consumer4<T, P1, P2, P3,P4> consumer, P1 p1, P2 p2, P3 p3,P4 p4) {
        Consumer<T> c = instance -> consumer.accept(instance, p1, p2, p3,p4);
        modifiers.add(c);
        return this;
    }

    public <P1, P2, P3,P4,P5> Builder<T> with(Consumer5<T, P1, P2, P3,P4,P5> consumer, P1 p1, P2 p2, P3 p3,P4 p4,P5 p5) {
        Consumer<T> c = instance -> consumer.accept(instance, p1, p2, p3,p4,p5);
        modifiers.add(c);
        return this;
    }

    public T build() {
        T value = instantiator.get();
        modifiers.forEach(modifier -> modifier.accept(value));
        modifiers.clear();
        return value;
    }
    

    /**
     * 1 参数 Consumer
     */
    @FunctionalInterface
    public interface Consumer1<T, P1> {
        /**
         * 接收参数方法
         * @param t 对象
         * @param p1 参数二
         */
        void accept(T t, P1 p1);
    }

    /**
     * 2 参数 Consumer
     */
    @FunctionalInterface
    public interface Consumer2<T, P1, P2> {
        /**
         * 接收参数方法
         * @param t 对象
         * @param p1 参数一
         * @param p2 参数二
         */
        void accept(T t, P1 p1, P2 p2);
    }

    /**
     * 3 参数 Consumer
     */
    @FunctionalInterface
    public interface Consumer3<T, P1, P2, P3> {
        /**
         * 接收参数方法
         * @param t 对象
         * @param p1 参数一
         * @param p2 参数二
         * @param p3 参数三
         */
        void accept(T t, P1 p1, P2 p2, P3 p3);
    }

    @FunctionalInterface
    public interface Consumer4<T, P1, P2, P3, P4>{
        /**
         * 接收参数方法
         * @param t 对象
         * @param p1 参数一
         * @param p2 参数二
         * @param p3 参数三
         * @param p4 参数四
         */
        void accept(T t,P1 p1,P2 p2,P3 p3,P4 p4);
    }

    @FunctionalInterface
    public interface Consumer5<T, P1, P2, P3, P4, P5>{
        /**
         * 接收参数方法
         * @param t 对象
         * @param p1 参数一
         * @param p2 参数二
         * @param p3 参数三
         * @param p4 参数四
         * @param p5 参数五
         */
        void accept(T t,P1 p1,P2 p2,P3 p3,P4 p4,P5 p5);
    }
}
  1. Builder调用方法
  1. Head
import lombok.*;

/**
 * @author Javacfox
 */
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = false)
public class Head {
    private String actionType;
    private String currentTime;
}
  1. Request
import com.alibaba.fastjson.JSONObject;
import com.infosec.ra.common.build.Builder;
import lombok.*;


/**
 * @author Javacfox
 */
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = false)
public class Request {
    private Head header;
    private JSONObject body;

    public void setHeader(String actiontype,String currenttime){
        this.header = Builder.of(Head::new)
                .with(Head::setActiontype,actiontype)
                .with(Head::setCurrenttime,currenttime)
                .build();
    }
}
  1. RequestBody
import com.alibaba.fastjson.JSONObject;
import com.infosec.ra.common.build.Builder;
import com.infosec.ra.common.build.outer.Signature;
import lombok.*;

/**
 * @author Javacfox
 */
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = false)
public class RequestBody {
    private Request request;
    private Signature signature;

    public void setRequest(String actiontype, String currenttime, JSONObject jsonObject){
        this.request = Builder.of(Request::new)
                .with(Request::setHeader,actiontype,currenttime)
                .with(Request::setBody,jsonObject)
                .build();
    }

    public void setSignature(String alg,String pubkey,String sign){
        this.signature = Builder.of(Signature::new)
                .with(Signature::setAlg,alg)
                .with(Signature::setPubkey,pubkey)
                .with(Signature::setSign,sign)
                .build();
    }
}
  1. 调用示例
public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uuid","1312321");
        jsonObject.put("devicetype","01");
        jsonObject.put("pubkey","dadadasdas");
        jsonObject.put("brand","");
        jsonObject.put("address","");
        jsonObject.put("email","");
        jsonObject.put("telephone","1312213");



        RequestBody requestBody = Builder.of(RequestBody::new)
                .with(RequestBody::setRequest, "", "", jsonObject)
                .with(RequestBody::setSignature, "sm3WithSm2", "asdsadas", "adssadas")
                .build();
        System.out.println(JSON.toJSONString(requestBody,SerializerFeature.SortField));
    }
  1. 结果打印
{
	"request":{
		"body":{
			"address":"",
			"telephone":"1312213",
			"uuid":"1312321",
			"brand":"",
			"devicetype":"01",
			"email":"",
			"pubkey":"dadadasdas"
		},
		"header":{
			"actiontype":"",
			"currenttime":""
		}
	},
	"signature":{
		"alg":"sm3WithSm2",
		"pubkey":"asdsadas",
		"sign":"adssadas"
	}
}

3.Builder代码简单讲解

  1. 通过Supplier懒加载的特性保存需要创建的对象
  2. 将每一步的操作保存到Consumer中,存入到List集合
  3. 在build方法中通过Supplier的get()方法获取实例,在遍历list调用每个Consumer的accept方法给该实例的参数进行初始化

自我推荐

这个是我的微信公众号,欢迎扫码关注,谢谢!
在这里插入图片描述

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
以下是一个 Java 代码示例,用于执行一个简单的 Elasticsearch 查询: ```java import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; import java.io.IOException; public class ElasticsearchQuery { public static void main(String[] args) throws IOException { // 创建 Elasticsearch 客户端 RestHighLevelClient client = createClient(); // 创建搜索请求对象 SearchRequest searchRequest = new SearchRequest("my_index"); // 构建搜索参数 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchQuery("title", "java")); sourceBuilder.sort("publish_date", SortOrder.DESC); sourceBuilder.size(10); sourceBuilder.timeout(TimeValue.timeValueSeconds(5)); searchRequest.source(sourceBuilder); // 执行搜索请求 SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); // 输出结果 System.out.println(searchResponse.toString()); // 关闭 Elasticsearch 客户端 client.close(); } private static RestHighLevelClient createClient() { // TODO: 创建 Elasticsearch 客户端并返回 } } ``` 在上面的代码中,我们创建了一个 Elasticsearch 客户端,并使用 `matchQuery` 方法构建了一个匹配查询,并按 `publish_date` 字段进行降序排序,并限制结果集大小为 10 条,并设置了超时时间为 5 秒。最后,我们执行了搜索请求,并输出了结果。 需要注意的是,上面的代码中的 `createClient` 方法需要根据具体的 Elasticsearch 集群进行实现。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笑不语

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值