構造器仍是構建器?

在實例化一個類的過程當中,一般會遇到多個參數的構造函數,但若是有些參數是非必需的呢?每次都要初始化那麼多參數麼?java

public class Person {
    private int id;//身份證號
    private String name;//姓名
    private int age;//年齡
    private boolean sex;//性別
    private String desc;//我的描述
    public Person(int id, String name, int age, boolean sex, String desc) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.desc = desc;
    }
}

或者像下面這樣,建立一個必選參數的構造器,在建立幾個可選參數的構造器?程序員

public Person(int id, String name) {//兩個參數的
        this.id = id;
        this.name = name;
    }

    public Person(int id, String name, int age) {//三個參數的
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Person(int id, String name, int age, boolean sex) {//四個參數的
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

或setter方法?安全

JavaBean模式自身有嚴重的缺點,由於構造過程被分到幾個調用中,在構造過程當中Javabean可能處於不一致的狀態,類沒法僅僅經過檢驗構造器參數的有效性來保證一致性。JavaBean模式阻止了把類作成不可變的可能,這就須要程序員付出額外的努力確保線程安全 ---摘自Effective Javaide

那麼咱們該怎樣用構建器來實現類的實例化而又不受制於構造函數限制呢?函數

public class Person {
    private final int id;//身份證號
    private final String name;//姓名
    private int age;//年齡
    private boolean sex;//性別
    private String desc;//我的描述
    private Person(Builder builder){
        this.id=builder.id;
        this.name=builder.name;
        this.age=builder.age;
        this.sex=builder.sex;
        this.desc=builder.desc;
    }
    public static class Builder{
        private final int id;
        private final String name;
        private int age;
        private boolean sex;
        private String desc;
        public Builder(int id, String name) {
            this.id = id;
            this.name = name;
        }
        public Builder age(int age){
            //年齡合法性檢查
            if(age<0)throw new IllegalArgumentException();
            else this.age=age;
            return this;
        }
        public Builder sex(boolean sex){
            this.sex=sex;
            return this;
        }
        public Builder desc(String desc){
            this.desc=desc;
            return this;
        }
        public Person build(){
            return new Person(this);
        }
    }

    @Override
    public String toString() {
        return "id:"+this.id+" 姓名:"+this.name+" 年齡:"+this.age+" 性別:"+this.sex+" 描述:"+this.desc;
    }
}

咱們在main函數中測試一下學習

public static void main(String[] args) {
        Builder builder=new Person.Builder(123,"張三");
        Person person=builder.age(18).sex(false).desc("好好學習,每天向上").build();
        System.out.println(person.toString());
    }

用構建器建立的實例易於閱讀和編寫,較javaBean模式又更加安全,天然,天然,每種方法都會有其優勢和弊端,選擇合適的使用場景,會讓代碼更加健壯易讀。測試

更多關於java的文章請戳這裏:(您的留言意見是對我最大的支持)

個人文章列表ui

Email:sxh13208803520@gmail.comthis

相關文章
相關標籤/搜索