你是否打过以下代码:
public class Animal{ private String name; private String breed; private String gender; private int weight; public Animal(String name, String breed) { this.name = name; this.breed = breed; } public Animal(String name, String breed,String gender,int weight) { this.name = name; this.breed = breed; this.gender=gender; this.weight=weight; } } 上述代码,导致了在构造过程中JavaBean可能处于不一致的状态,也就是说实例化对象本该是一气呵成,但现在却分割成了两大步,这会导致它线程不安全,进一步引发不可预知的后果。 Effective+Java作者joshua bloch推荐利用"Builder"模式(构造者模式),其核心就是不直接生成想要的对象,而是让客户端利用所有必要的参数调用构造器(或者静态工厂), 得到一个builder对象,再调用类似setter的方法设置相关可选参数。 代码如下: public class Animal{ private String name; private String breed; private String gender; private int weight; public static class Builder { private String name; private String breed; private String gender; private int weight; public Builder(String name, int weight){ this.name=name; this.weight=weight; } public Builder gender(String gender){ this.gender=gender; return this; } public Builder breed(String breed){ this.breed=breed; return this; } public Animal build(){ return new Animal(this); } } private Animal(Builder builder){ this.name=builder.name; this.breed=builder.breed; this.gender=builder.gender; this.weight=builder.weight; } } 调用: Animal animal=new Animal.Builder("Tom",10).breed("Cat").build();