可以看到这个学生类的属性是非常多的,所以构造方法不是一般的长,如果我们现在直接通过new的方式去创建:
可以看到,我们光是填参数就麻烦,我们还得一个一个对应着去填,一不小心可能就把参数填到错误的位置了。
所以,我们现在可以使用建造者模式来进行对象的创建:
java;gutter:true;
class Student {
private int id;
private int age;
private String name;
private String college;
private String profession;
private List hobby;</p>
<pre><code>// 设置为私有,只给内部类用
private Student(int id, int age, String name, String college, String profession, List hobby) {
this.id = id;
this.age = age;
this.name = name;
this.college = college;
this.profession = profession;
this.hobby = hobby;
}
/**
* 获取建造者
*
* @return 建造者
*/
public static StudentBuild build() {
return new StudentBuild();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public List getHobby() {
return hobby;
}
public void setHobby(List hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
", college='" + college + '\'' +
", profession='" + profession + '\'' +
", hobby=" + hobby +
'}';
}
public static class StudentBuild {
//Builder也需要将所有的参数都进行暂时保存,所以Student怎么定义的这里就怎么定义
private int id;
private int age;
private String name;
private String college;
private String profession;
private List hobby;
// 这里返回this是为了链式调用
public StudentBuild id(int id) {
this.id = id;
return this;
}
public StudentBuild age(int age) {
this.age = age;
return this;
}
public StudentBuild name(String name) {
this.name = name;
return this;
}
public StudentBuild college(String college) {
this.college = college;
return this;
}
public StudentBuild profession(String profession) {
this.profession = profession;
return this;
}
public StudentBuild hobby(String... hobby) {
this.hobby = Arrays.asList(hobby);
return this;
}
public Student build() {
return new Student(id, age, name, college, profession, hobby);
}
}
</code></pre>
<p>}</p>
<pre><code>
现在,我们就可以使用建造者来为我们生成对象了:
;gutter:true;
public static void main(String[] args) {
Student student = Student.build()
.id(1)
.age(23)
.name("张三")
.college("信息工程学院")
.profession("学生")
.hobby("抽烟", "喝酒", "烫头")
.build();
//Student{id=1, age=23, name=’张三’, college=’信息工程学院’, profession=’学生’, hobby=[抽烟, 喝酒, 烫头]}
System.out.println(student);
}
Original: https://www.cnblogs.com/zhangzhixi/p/16405436.html
Author: Java小白的搬砖路
Title: 建造者设计模式
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/612703/
转载文章受原作者版权保护。转载请注明原作者出处!