lombok中的@builder是怎么实现的?

比如有个Aliyun类,其中有以下几个属性:appKey,appSecret,bucket,endPoint。使用lombok的时候我们只需要加上一个@Builder注解就可以使用建造者模式构建对象。

那么这个@builder是怎样做到的呢?以下demo基本是他的原理了。

public class Aliyun {
  private String appKey;
  private String appSecret;
  private String bucket;
  private String endPoint;

  public static class Builder{
    private String appKey;
    private String appSecret;
    private String bucket;
    private String endPoint;

    public Builder appKey(String appKey) {
      this.appKey = appKey;
      return this;
    }

    public Builder appSecret(String appSecret) {
      this.appSecret = appSecret;
      return this;
    }

    public Builder bucket(String bucket) {
      this.bucket = bucket;
      return this;
    }

    public Builder endPoint(String endPoint) {
      this.endPoint = endPoint;
      return this;
    }

    public Aliyun build() {
      return new Aliyun(this);
    }

  }

  public static Builder builder() {
    return new Aliyun.Builder();
  }

  private Aliyun(Builder builder) {
    this.appKey = builder.appKey;
    this.appSecret = builder.appSecret;
    this.bucket = builder.bucket;
    this.endPoint = builder.endPoint;
  }

  @Override
  public String toString() {
    return "Aliyun{" +
        "appKey='" + appKey + '\'' +
        ", appSecret='" + appSecret + '\'' +
        ", bucket='" + bucket + '\'' +
        ", endPoint='" + endPoint + '\'' +
        '}';
  }
}

 

在使用上是一样的:

Aliyun aliyun = Aliyun.builder()
    .appKey("123")
    .appSecret("456")
    .bucket("789")
    .endPoint("0")
    .build();
System.out.println(aliyun);
posted @ 2019-12-30 10:33  苦瓜爆炒牛肉  阅读(1499)  评论(0编辑  收藏  举报