Effective Java之创建和初始化对象
重载构造方法
public class CreateObject1 {
private String name;
private String sex;
private Integer age;
private String addr;
public CreateObject1(String name,String sex) {
this(name, sex, 0, null);
}
public CreateObject1(String name,String sex, Integer age) {
this(name, sex,age, null);
}
public CreateObject1(String name, String sex,Integer age, String addr) {
this.name = name;
this.sex = sex;
this.age = age;
this.addr = addr;
}
}
调用情况
CreateObject1 createObject1 = new CreateObject1("白羽流光", "男", 26, "杭州市");
这种方式初始化和创建对象是我们在平时工作中经常用的,但是一旦增加更多的字段就会变得很难维护也很麻烦。而且这种创建方式比较难阅读,很多情况下我们无法一眼可以知道各个参数的含义。
JavaBean模式
public class CreateObject2 {
private String name;
private String sex;
private Integer age;
private String addr;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}
调用情况
CreateObject2 createObject2 = new CreateObject2();
createObject2.setName("白羽流光");
createObject2.setSex("男");
createObject2.setAge(26);
createObject2.setAddr("杭州市");
这种方式创建实例很容易也更方便阅读了,但是因为构造过程被分到了几个调用,这样创建一个对象其他函数可以获得对象后通过set进行篡改这个对象里的值,非常得不安全。
Builder 模式
public class CreateObject3 {
private String name;
private String sex;
private Integer age;
private String addr;
public static class Builder {
private String name;
private String sex;
//可变的附上初始化值
private Integer age = 0;
private String addr = null;
public Builder(String name, String sex) {
this.name = name;
this.sex = sex;
}
public Builder age(Integer var) {
age = var;
return this;
}
public Builder addr(String var) {
addr = var;
return this;
}
private CreateObject3 build(){
return new CreateObject3(this);
}
}
public CreateObject3(Builder builder) {
this.name = builder.name;
this.sex = builder.sex;
this.age = builder.age;
this.addr = builder.addr;
}
}
调用情况
CreateObject3 createObject3 = new CreateObject3.Builder("白羽流光", "男").age(26).addr("杭州市").build();
这个模式兼顾了可读性,也比较安全,后续无法改变对象中的属性值。
学习如逆水行舟,不进则退。