一、创建、销毁对象
1、考虑用静态工厂方法替代构造器
2、遇到多个构造器参数时要考虑用构建器
静态工厂和构造器有一个共同的局限性,它们不能很好的扩展到大量的可选参数,程序员一向习惯采用重叠构造器,在这种模式下,提供第一个只有必要参数的构造器,第二个构造器有一个可选参数,最后一个构造器包含所有的可选参数。
public People(String name,String sex){
this(name,sex,0,0,0,"");
}
public People(String name,String sex,int age){
this(name,sex,age,0,0,"");
}
public People(String name,String sex,int age,float height,float wigth){
this(name,sex,age,height,wigth,"");
}
public People(String name,String sex,int age,float height,float wigth,String skin){
this.name=name;
this.sex=sex;
this.age=age;
this.height=height;
this.wigth=wigth;
this.skin=skin;
}
重叠的构造器方法可行,但是当有许多参数的时候,代码很难编写,并且难以阅读。
Builder方法:
public class People {
private final String name;
private final String sex;
private final String address;
private final float height;
private final float weight;
public People(Builder builder) {
name = builder.name;
sex = builder.sex;
address = builder.address;
height = builder.height;
weight = builder.weight;
}
}
public class Builder {
public String name;
public String sex;
public String address;
public float height;
public float weight;
public Builder(String name, String sex) {
this.name = name;
this.sex = sex;
}
public Builder setAddress(String address) {
this.address = address;
return this;
}
public Builder setHeight(float height) {
this. height = height;
return this;
}
public Builder setWeight(float weight) {
this.weight = weight;
return this;
}
public People build() {
return new People(this);
}
}
public class MainClass {
public static void main(String[] args){
People people = new Builder("pxc","女").setAddress("福州").setHeight(163).setWeight(45).build();
}
}
运行结果:通过builder方法把参数写入对象中。
Builder模式易于阅读,参数灵活。
第四章 类和接口
1、使类和成员的可访问性最小化:尽可能使每个类或者成员不被外界访问。
实例域不能是共有的:包含共有可变域的类并不是线程安全的。
2、使可变性最小化
2.1 不提供任何机会会修改对象状态的方法
2.2 保证类不会被扩展