第二章第2条:遇到多个构造器参数时要考虑使用构建器(builder)

就是建造者模式(不直接生成想要的对象,而是让客户端利用所有有必要的参数调用构造器或者静态工厂)直接上代码

package com.edu.character02;

/**
* <p>
* builder Pattern
* </p>
*
* @作者 five-five
* @创建时间 2020/8/4
*/
public class Student {
private int id;//必填
private String name;//必填
private String sex;
private String address; public static class Builder {
private final int id;//必填
private final String name;//必填
private String sex = "男";
private String address = "湖南"; //返回对象,可以流式编写代码
public Builder(int id, String name) {
this.id = id;
this.name = name;
} public Builder sex(String sex) {
this.sex = sex;
return this;
} public Builder address(String address) {
this.address = address;
return this;
} public Student build() {
return new Student(this);
}
} private Student(Builder builder) {
this.id = builder.id;
this.name = builder.name;
this.sex = builder.sex;
this.address = builder.address;
} @Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}

测试代码:

package com.edu.character02;

/**
* @作者 five-five
* @创建时间 2020/8/4
*/
public class TestStudent {
public static void main(String[] args) {
Student student=new Student.Builder(1,"鸣人").sex("男").address("湖南").build();
System.out.println(student);
}
}

测试结果:effective java之使用构建器来创建对象-LMLPHP

05-11 18:11