1. 程式人生 > >Java Builder模式的寫法和lombok外掛@Builder註解的支援

Java Builder模式的寫法和lombok外掛@Builder註解的支援

1. Builder模式簡化get set方法,只需要定義一個靜態公共的內部類即可
public class User {
    private Integer id;
    private String name;
    private String address;

    private User() {
    }

    private User(User origin) {
        this.id = origin.id;
        this.name = origin.name;
        this.address = origin.address;
} public static class Builder { private User target; public Builder() { this.target = new User(); } public Builder id(Integer id) { target.id = id; return this; } public Builder name(String name) { target.
name = name; return this; } public Builder address(String address) { target.address = address; return this; } public User build() { return new User(target); } }
2.如果專案中有使用lombok的話,可以直接使用@Builder註解來實現

定義工具類如下:

import lombok.Builder;
import lombok.ToString;

/**
 * @author wulongtao
 */
@ToString
@Builder
public class UserExample {
    private Integer id;
    private String name;
    private String address;
}

使用方法:

UserExample userExample = UserExample.builder()
                .id(1)
                .name("aaa")
                .address("bbb")
                .build();

System.out.println(userExample);