在实际开发过程中,我们一般通过构造方法将参数传入一般的实体类,而且实体类的构造方法可能不止一个,当参数个数过多时,伴随而来的是构造方法数量的上升,过多的构造方法参数往往给用户带来一种不明就里的感觉。
构造器模式的出现很好的解决了多参数初始化的问题。假设我们需要编写一个Student类,此类含有四个属性,代码如下:
public class Student {
private String id;
private String name;
private int age;
private Date birth;
public Student(String id){
this(id,null,0,null);
}
public Student(String id, String name){
this(id,name,0,null);
}
public Student(String id, String name, int age){
this(id,name,age,null);
}
public Student(String id, String name, int age, Date birth){
this.id = id;
this.name = name;
this.age = age<0?0:age;
this.birth = birth;
}
}
该类针对不同个数的参数提供了四个构造方法,当我们需要创建对象时,我们可能会这么写
Student student = new Student("100000011","Alex",18);
看似简洁明了,但是很难说清楚每个参数的含义,不易于理解。
那我们换一种思路,对象不是通过new创建的,而是通过一种类似set的方法链的方式来设置的,最后返回一个Student对象。
public class Student {
private String id;
private String name;
private int age;
private Date birth;
public Student(String id){
this(id,null,0,null);
}
public Student(String id, String name){
this(id,name,0,null);
}
public Student(String id, String name, int age){
this(id,name,age,null);
}
public Student(String id, String name, int age, Date birth){
this.id = id;
this.name = name;
this.age = age<0?0:age;
this.birth = birth;
}
public Student(Student student){
this.id = student.id;
this.name = student.name;
this.age = student.age;
this.birth = student.birth;
}
public static class Builder{
private Student target;
public Builder id(String id){
target.id = id;
return this;
}
public Builder name(String name){
target.name = name;
return this;
}
public Builder age(int age){
target.age = age;
return this;
}
public Builder birth(Date birth){
target.birth = birth;
return this;
}
public Student build() {
return new Student(target);
}
}
}
这时我们可以使用如下方式创建对象
Student student = new Student.Builder().id("10000011").name("Alex").age(18).birth(new Date()).build();
构造器模式将构造器的setter方法名取成类似注释的方式,这样我们可以很清晰的知道刚才究竟设置的什么值,可读性较高,缺点是比较冗长。