effective java 第2條:遇到多個構造器引數時要考慮用構造器

zhumeilu發表於2017-12-14

如果構建一個物件需要很多引數時,那麼有三種方式可以實現。 第一種就是多重構造器

public class Person {

    private final int id;           //required
    private final String name;      //required
    private final int age;          //optional
    private final int gender;          //optional
    private final Date brithDay;          //optional
    
    public Person(int id, String name, int age, int gender, Date brithDay) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.brithDay = brithDay;
    }
    public Person(int id, String name, int age, int gender){
        this(id, name, age, gender, null);
    }
    public Person(int id, String name, int age){
        this(id, name, age, 0);
    }
    public Person(int id, String name){
        this(id, name,0);
    }
}
複製程式碼

第二種JavaBean 通過setter設定引數 缺點:因為構造過程被分到了幾個呼叫中,在構造過程中JavaBean可能處於不一致的狀態。 第三種Builder構建器模式

public class Person {

    private final int id;           //required
    private final String name;      //required
    private final int age;          //optional
    private final int gender;          //optional
    private final Date birthday;          //optional

    public static class Builder implements com.zml.Builder<Person>{

        private int id;           //required
        private String name;      //required
        private int age = 0;          //optional
        private int gender = 0;          //optional
        private Date birthday = null;          //optional

        public Builder(int id,String name){
            this.id = id;
            this.name = name;
        }
        public Builder age(int age){
            this.age = age;
            return this;
        }
        public Builder gender(int gender){
            this.gender = gender;
            return this;
        }
        public Builder brithDay(Date brithDay){
            this.birthday = brithDay;
            return this;
        }

        @Override
        public Person builder() {
            return new Person(this);
        }
    }

    public Person(Builder builder) {
        this.id = builder.id;
        this.name = builder.name;
        this.age = builder.age;
        this.gender = builder.gender;
        this.birthday = builder.birthday;
    }

    public static void main(String[] args) {
        Person person = new Person.Builder(1,"hello").builder();
    }
}
public interface Builder<T> {
    T builder();
}
複製程式碼

相關文章