解决静态工厂和构造函数不能很好的扩展大量的可选参数,采用如下的两个方案解决
javaBean:
通过无参构造实例化一个对象,在调用setter方法来设定每一个必要/可选参数
构建器builder(只在很多参数才使用)
public class Student {
// 必要参数
private final int age;
private final String sex;
// 可选参数
private final int tall;
private final String name;
// 构造函数
private Student(Bulider bulider) {
age = bulider.age;
sex = bulider.sex;
tall = bulider.tall;
name = bulider.name;
}
/*
* 构建bulidre类
*/
public static class Bulider {
// 必要参数
private final int age;
private final String sex;
// 可选参数
private int tall = 0;
private String name = "";
public Bulider(int age, String sex) {
this.age = age;
this.sex = sex;
}
/**
* 对可选参数进行构建
*/
public Bulider tall(int tall) {
this.tall = tall;
return this;
}
public Bulider name(String name) {
this.name = name;
return this;
}
// 返回构建的实例,关联student类
public Student bulid() {
return new Student(this);
}
}
}
使用:
Student student = new Student.Bulider(20, "男").bulid();
Student student = new Student.Bulider(20, "男").tall(150).bulid();