builder方法来构造对象
利用Builder来构建对象
优势:通常构造对象的方法有两种。一、全参数构造方法;二、无参构造函数,然后通过get和set方法。
第一种很多参数不需要设置,而且可能弄混;
第二种每一个值都要set一次,设置起来很累。
然后就有Builder对象链式编程来简化构造对象,原理就是返回this对象,就是返回本身,来达到链式编程的目的。
如下图,Refactor自动生成builder方法
@Data
public class BasicStudent {
private int id;
private String name;
private String sex;
private Integer age;
BasicStudent(int id, String name, String sex, Integer age) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
public static BasicStudentBuilder builder() {
return new BasicStudentBuilder();
}
public static class BasicStudentBuilder {
private int id;
private String name;
private String sex;
private Integer age;
BasicStudentBuilder() {
}
public BasicStudentBuilder id(int id) {
this.id = id;
return this;
}
public BasicStudentBuilder name(String name) {
this.name = name;
return this;
}
public BasicStudentBuilder sex(String sex) {
this.sex = sex;
return this;
}
public BasicStudentBuilder age(Integer age) {
this.age = age;
return this;
}
public BasicStudent build() {
return new BasicStudent(id, name, sex, age);
}
@Override
public String toString() {
return "BasicStudent.BasicStudentBuilder(id=" + this.id + ", name=" + this.name + ", sex=" + this.sex + ", age=" + this.age + ")";
}
}
}
BasicStudent basicStudent = BasicStudent.builder()
.id(1)
.name("yorkiiz")
.sex("male")
.build();
如果觉得这样麻烦,可以使用注解来自动生成builder
@Builder
@Data
public class BasicStudent {
private int id;
private String name;
private String sex;
private Integer age;
}
@Builder注解会遇到的问题
Entity上加上@Builder,会默认为类加上全参构造函数。这样显示声明了全参构造函数,那么默认的无参构造函数就会失效,导致很多通过反射的方法来构造对象就会失败。
所以最好是以下三个注解同时使用
@Builder
@NoArgsConstructor
@AllArgsConstructor
参考链接:https://blog.csdn.net/xsj_blog/article/details/97293751