遇到多個構造器引數時考慮使用構建器(Effective Java )

weixin_34249678發表於2017-06-08

當一個複雜的物件的構造有許多可選引數的時候,就應該考慮使用構建器(Builder設計模式)來構建物件。

5321358-375af7da75231219.png
Paste_Image.png

一般來說, Builder常常作為實際產品的靜態內部類來實現(提高內聚性).
故而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(">>發動機>>");
        }

        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:>>車身>>>>輪子>>>>發動機>>>>座椅>>
        Car caeTwo = new Car.Builder().withModel().withSeat().withWheel().build();
        System.out.println("Car2 has: " + caeTwo);
        //Car2 has: A car has:>>車身>>>>輪子>>>>座椅>>
    }

相關文章