说到多个构造器参数,第一个想到的应该是重叠构造器模式:
public class UserModel {
private String ID;
private String name;
private String sex;
private String password;
private String tel;
public UserModel(String ID, String password) {
this(ID, password, null);
}
public UserModel(String ID, String password, String sex) {
this(ID, password, sex, null);
}
public UserModel(String ID, String password, String sex, String name) {
this(ID, password, sex, name, null);
}
public UserModel(String ID, String password, String sex,
String name, String tel) {
this.ID = ID;
this.name = name;
this.sex = sex;
this.password = password;
this.tel = tel;
}
}
这种最简单也最“pia气”的方法,在许多参数的时候极易失去控制并出错,谁会喜欢一个个数这个参数是第几个呢?显然不合理;
这个时候就有了JavaBeans模式。例:
public class UserModel {
private String ID;
private String name;
private String sex;
private String password;
private String tel;
public UserModel() {
}
public UserModel setID(String iD) {
this.ID = iD;
return this;
}
public UserModel setName(String name) {
this.name = name;
return this;
}
public UserModel setSex(String sex) {
this.sex = sex;
return this;
}
public UserModel setPassword(String password) {
this.password = password;
return this;
}
public UserModel setTel(String tel) {
this.tel = tel;
return this;
}
}
使用方法:
UserModel model = new UserModel().setID("0001")
.setName("funyoo")
.setSex("男")
.setPassword("password")
.setTel("123456789");
用这种形式写出的代码相比重叠可读性非常的高
但是,JavaBeans模式阻止了把类做成不可变的可能。这个时候程序员就可能会付出额外的努力来保证它的线程安全!
这个时候就引出了第三种构造器,即有重叠构造器的安全性,也有JavaBeans模式的易读性;
package com.funyoo.mis.model;
public class UserModel {
private final String ID;
private final String name;
private final String sex;
private final String password;
private final String tel;
public static class Builder {
private final String ID;
private final String password;
private String name = null;
private String sex = null;
private String tel = null;
public Builder(String ID, String password) {
this.ID = ID;
this.password = password;
}
public Builder setSex(String sex) {
this.sex = sex;
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setTel(String tel) {
this.tel = tel;
return this;
}
public UserModel builder() {
return new UserModel(this);
}
}
private UserModel(Builder builder) {
ID = builder.ID;
name = builder.name;
sex = builder.sex;
password = builder.password;
tel = builder.tel;
}
}
使用方法:
UserModle model = new UserModel.Builder("0001", "password")
.setName("funyoo")
.setSex("男")
.setTel("123456789")
.builder();
这种方式显然要比JavaBeans模式要安全的多。
—— 2018年9月于《Effective Java》学到以上内容,在此分享