平常我们新建对象的时候,一般是直接
Student student = new Student("zhangsan",11,new Date(),"男");
这样的代码可读性极差。
使用构造器模式
Student student = new Student
.StudentBuilder("张三")
.date(new Date())
.address("江苏")
.gender("男")
.build();
这样让人可以在看代码的时候,一目了然
下面是具体代码实现:(很简单的啦)
package com.husky.pojo;
import java.util.Date;
/**
* @author husky
* @date 2018/9/12 19:47
*/
public class Student {
private String name;
private Date date;
private String address;
private String gender;
public Student() {
super();
}
public Student(StudentBuilder studentBuilder) {
this.name = studentBuilder.name;
this.date = studentBuilder.date;
this.address = studentBuilder.address;
this.gender = studentBuilder.gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", date=" + date +
", address='" + address + '\'' +
", gender='" + gender + '\'' +
'}';
}
public static class StudentBuilder {
private String name;
private Date date;
private String address;
private String gender;
public String getName() {
return name;
}
public Date getDate() {
return date;
}
public String getAddress() {
return address;
}
public String getGender() {
return gender;
}
public StudentBuilder(String name){
this.name = name;
}
public StudentBuilder date(Date date){
this.date = date;
return this;
}
public StudentBuilder address(String address){
this.address = address;
return this;
}
public StudentBuilder gender(String gender){
this.gender = gender;
return this;
}
public Student build(){
return new Student(this);
}
}
}
测试
Student student = new Student
.StudentBuilder("张三")
.date(new Date())
.address("江苏")
.gender("男")
.build();
System.out.println(student);
这种写法有点像jdk8的流式写法,但是缺点却是很显然,自己写builder的时候十分烦躁,代码冗余