写在前面
以下规则只适应于"多个构造参数的建造者模式"。
使用场景
遇到多个构造器参数时要考虑用构建者模式。
核心思想
A. 将改造对象的所有属性声明为final;
B. 在改造的对象中添加一个静态类Builer(public static class Builder );
C. 静态类Builder中的属性和该对象的属性一样,唯一不同的是静态类中的属性是非final声明的;
D. 静态类Builer中会包含1个以上的带有参数的Builer构造器,一般提供的带参数的该构造器中的参数是描述该对象的最最基本的属性;
E. 静态类Builer中提供多个返回类型为Builder的set方法用于进行构造,在set完属性以后加上该代码"return this";
F. 静态类Builer中还包含一个build方法,返回类型为该改造的对象,改造对象提供一个构造器,他的构造参数为Builder对象,在该构造器中通过Builder对象初始化final属性。
改造前
package com.rocky.learn.l004.t3;
@SuppressWarnings("unused")
public class Student1 {
private String name;
private int age;
private int height;
private int sex; // 1 - 男, 0 - 女
private String schoolName;
private String profession;
private int gradeNo;
public Student1(String name, int age, int height, int sex) {
super();
this.name = name;
this.age = age;
this.height = height;
this.sex = sex;
}
public Student1(String name, int age, int height, int sex, String schoolName, String profession) {
super();
this.name = name;
this.age = age;
this.height = height;
this.sex = sex;
this.schoolName = schoolName;
this.profession = profession;
}
public Student1(String name, int age, int height, int sex, String schoolName, String profession, int gradeNo) throws Exception {
super();
this.name = name;
this.age = age;
this.height = height;
this.sex = sex;
this.schoolName = schoolName;
this.profession = profession;
this.gradeNo = gradeNo;
}
}
改造后
// 使用建造者模式的代码如下Student2.java:
package com.rocky.learn.l004.t3;
@SuppressWarnings("unused")
public class Student2 {
private final String name;
private final int age;
private final int height;
private final int sex; // 1 - 男, 0 - 女
private final String schoolName;
private final String profession;
private final int gradeNo;
private Student2(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.height = builder.height;
this.sex = builder.sex;
this.schoolName = builder.schoolName;
this.profession = builder.profession;
this.gradeNo = builder.gradeNo;
}
public static class Builder {
private String name;
private int age;
private int height;
private int sex;
private String schoolName;
private String profession;
private int gradeNo;
public Builder(String name, int age, int height, int sex) {
super();
this.name = name;
this.age = age;
this.height = height;
this.sex = sex;
}
public Builder setSchoolName(String schoolName) {
this.schoolName = schoolName;
return this;
}
public Builder setProfession(String profession) {
this.profession = profession;
return this;
}
public Builder setGradeNo(int gradeNo) {
this.gradeNo = gradeNo;
return this;
}
public Student2 build() {
return new Student2(this);
}
}
}
如何使用?
Student2 student = new Student2.Builder("ROCKY", 30, 185, 1)
.setSchoolName("清华大学")
.setGradeNo(2)
=.build();