当某个类中有多个参数时,如果在构造方法中提供参数的设置,将会出现数量众多的组合,代码可读性会非常差
此处例子只有3个参数,构造方法已经众多,并且还有参数类型之间的冲突问题
public class Student {
private Long id;
private String name;
private String phoneNumber;
//......
public Student() {
}
public Student(Long id) {
this.id = id;
}
public Student(String name) {
this.name = name;
}
public Student(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}
public Student(Long id, String name) {
this.id = id;
this.name = name;
}
public Student(Long id, String name, String phoneNumber) {
this.id = id;
this.name = name;
this.phoneNumber = phoneNumber;
}
//......
}
改用set方法来优化:
public class Student {
private Long id;
private String name;
private String phoneNumber;
public Student() {
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
在使用时:
Student student = new Student();
student.setId(123L);
student.setName("name");
student.setPhoneNumber("123456");
但是,set方法在使用时会有线程安全的问题
假如上述代码块在执行到setId时student就被另一线程调用,此时Name和PhoneNubmer就会为null,而如果给student加锁,则会影响性能,改用builder则能解决这些问题:
public class Student {
private Long id;
private String name;
private String phoneNumber;
private Student(StudentBuiler builer) {
this.id = builer.id;
this.name = builer.name;
this.phoneNumber = builer.phoneNumber;
}
public static class StudentBuiler {
private Long id;
private String name;
private String phoneNumber;
public StudentBuiler id(Long id) {
this.id = id;
return this;
}
public StudentBuiler name(String name) {
this.name = name;
return this;
}
public StudentBuiler phoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
return this;
}
public Student build() {
return new Student(this);
}
}
}
在调用时的代码也简洁明了:
Student student = new Student.StudentBuiler().id(123L).name("name").phoneNumber("123456").build();