编程语言
首页 > 编程语言> > java – lombok – 多个镜头中的@Builder模式

java – lombok – 多个镜头中的@Builder模式

作者:互联网

我使用lombok project的@Builder,所以请考虑我有这个例子:

@Builder
public class Client {

    private @Getter @Setter Integer id;
    private @Getter @Setter String name;

}

这相当于:

public class Client {

    private @Getter @Setter Integer id;
    private @Getter @Setter String name;

    public static class Builder {

        private Integer id;
        private String name;

        private Builder() {
        }

        public Builder id(final Integer value) {
            this.id = value;
            return this;
        }

        public Builder name(final String value) {
            this.name = value;
            return this;
        }

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

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

    private Client(final Builder builder) {
        this.id = builder.id;
        this.name = builder.name;
    }
}

当我尝试一次性设置所有字段时没有问题:

public static void main(String[] args) {
    Client client = Client.builder()
            .id(123)
            .name("name")
            .build();
}

输出:

Client{id=123, name=name}

现在,考虑我想要多次拍摄.例如:

public static void main(String[] args) {
    Client client = Client.builder()
            .id(123)//<-------------------------- Set just the id
            .build();

    client = Client.builder()
            .name("name")//<--------------------- Set name
            .build();

}

这在逻辑上为id返回null:

Client{id=null, name=name}

通常,没有lombok,我通过在Builder类中添加一个新的构造函数来解决这个问题,该构造函数采用相同的对象:

public static class Builder {
    // ...
    public Builder(Client client) {
        this.id = client.id;
        this.name = client.name;
    }
    // ...
}

然后我将我的对象传递给该构造函数:

Client client = Client.builder()
        .id(123)
        .build();

client = new Client.Builder(client)//<---------------- Like this 
        .name("name")
        .build();

这解决了我的问题,但我不能用lombok来解决它.有什么方法可以解决这个问题吗?

解决方法:

您可以使用toBuilder属性来执行此操作.

@Builder(toBuilder=true)
public class Client {
    private @Getter @Setter Integer id;
    private @Getter @Setter String name;
}

然后你可以这样使用它

public void main(String[] args){
    Client client = Client.builder()
        .id(123)
        .build();

    client = client.toBuilder()
        .name("name")
        .build();
}

标签:java,lombok,builder-pattern
来源: https://codeday.me/bug/20190717/1486476.html