遇到多個構(gòu)造器參數(shù)時考慮使用構(gòu)建器(Effective Java )

當(dāng)一個復(fù)雜的對象的構(gòu)造有許多可選參數(shù)的時候,就應(yīng)該考慮使用構(gòu)建器(Builder設(shè)計模式)來構(gòu)建對象。

Paste_Image.png

一般來說, Builder常常作為實際產(chǎn)品的靜態(tài)內(nèi)部類來實現(xiàn)(提高內(nèi)聚性).
故而Product,Director, Builder常常是在一個類文件中, 例如本例中的Car.java.

public class Car {
    // 這邊就隨便定義幾個屬性
    private boolean addModel;
    private boolean addWheel;
    private boolean addEngine;
    private boolean addSeat;

    public Car(Builder builder) {
        this.addModel = builder.addModel;
        this.addWheel = builder.addWheel;
        this.addEngine = builder.addEngine;
        this.addSeat = builder.addSeat;
    }

    @Override
    public String toString() {

        StringBuilder builder = new StringBuilder("A car has:");

        if (this.addModel) {
            builder.append(">>車身>>");
        }

        if (this.addWheel) {
            builder.append(">>輪子>>");
        }

        if (this.addEngine) {
            builder.append(">>發(fā)動機>>");
        }

        if (this.addSeat) {
            builder.append(">>座椅>>");
        }

        return builder.toString();
    }

    public static class Builder {

        private boolean addModel;
        private boolean addWheel;
        private boolean addEngine;
        private boolean addSeat;

        public Builder() {

        }

        public Builder withModel() {
            this.addModel = true;
            return this;
        }

        public Builder withWheel() {
            this.addWheel = true;
            return this;
        }

        public Builder withEngine() {
            this.addEngine = true;
            return this;
        }

        public Builder withSeat() {
            this.addSeat = true;
            return this;
        }

        public Car build() {
            return new Car(this);
        }
    }

    public static void main(String[] args) {
             // build car
        Car carOne = new Car.Builder().withModel().withModel().withEngine().withSeat().withWheel().build();
        System.out.println("Car1 has: " + carOne);
        //Car1 has: A car has:>>車身>>>>輪子>>>>發(fā)動機>>>>座椅>>
        Car caeTwo = new Car.Builder().withModel().withSeat().withWheel().build();
        System.out.println("Car2 has: " + caeTwo);
        //Car2 has: A car has:>>車身>>>>輪子>>>>座椅>>
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容