定义 Builder 接口,用于 build 对象:
public interface Builder<T> {
T build();
}
定义 bean:
import lombok.Getter
@Getter
public class UserFacts {
private String name;
private Integer age;
public static UserFactsBuilder builder() {
return new UserFactsBuilder();
}
public static class UserFactsBuilder implements Builder<UserFacts> {
private String name;
/**
* 可设置默认值
*/
private Integer age = 18;
public UserFactsBuilder name(String name) {
this.name = name;
return this;
}
public UserFactsBuilder age(Integer age) {
this.age = age;
return this;
}
@Override
public UserFacts build() {
return new UserFacts(this);
}
}
private UserFacts(UserFactsBuilder builder) {
this.name = builder.name;
this.age = builder.age;
}
}
测试:
public static void main(String[] args) {
UserFacts userFacts = UserFacts.builder()
.name("https")
.age(18)
.build();
System.out.println(userFacts.getName());
}
标签:name,UserFacts,age,public,如何,UserFactsBuilder,Lombok,Builder
From: https://www.cnblogs.com/Higurashi-kagome/p/17366198.html