未使用Builder模式
假设有一个Student代表学生类,里面有很多属性,如下:
public class Student {
private int id;
private int age;
private int sex;
private float weight;
private String name;
private String major;
private String grade;
}
如果我们需要创建一个Student类,可能增加如下构造方法:
public Student(int id, int age, int sex, float weight, String name, String major, String grade) {
this.id = id;
this.age = age;
this.sex = sex;
this.weight = weight;
this.name = name;
this.major = major;
this.grade = grade;
}
此时我们创建一个Student类:
Student student=new Student(1,25,0,120,"小明","Android","初级");
看到上面创建Student对象,是不是会觉得构造方法中参数那么多,他们分别代表什么呢?是不是看起来很不清晰明了
使用Builder模式
下面将使用Builder模式来进行改善:
- 在Student类中创建一个内部静态类Builder,该类包含Student中所有的属性
public class Student {
public static class Builder{
private int id;
private int age;
private int sex;
private float weight;
private String name;
private String major;
private String grade;
...
}
}
- 为每个属性创建一个类似setXXX的方法,但该方法返回值为Builder
public class Student {
public static class Builder{
...
public Builder id(int id){
this.id=id;
return this;
}
public Builder age(int age){
this.age=age;
return this;
}
...
}
}
- 在Student中创建一个包含Builder的私有构造方法,并将Builder中的属性赋值给对应Student中的属性
private Student(Builder builder){
this.id=builder.id;
this.age=builder.age;
this.sex=builder.sex;
this.weight=builder.weight;
this.name=builder.name;
this.major=builder.major;
this.grade=builder.grade;
}
- 在Builder中创建一个build()方法,该方法返回Student对象
public class Student {
public static class Builder{
...
public Student build(){
Student student=new Student(this);
return student;
}
...
}
}
使用Builder模式构建一个Student对象
Student student=new Student.Builder()
.id(1)
.name("小明")
.age(18)
.sex(0)
.weight(120)
.major("Android")
.grade("初级")
.build();
总结
Builder设计模式将创建对象交给内部类Builder,Builder类中含有外部类所需的属性,Builder负责给外部类属性赋值,从而来构建外部类对象。
从上面的对比看出,使用Builder模式提高了代码的可读性,但是与此同时代码量增加了不少。
因此如果对于一个对象中有大量属性的情况下,使用Builder模式将大大提高代码的可读性。
网友评论