美文网首页Effective Java
遇到多个构造器参数时考虑使用构建器(Effective Java

遇到多个构造器参数时考虑使用构建器(Effective Java

作者: yht_humble | 来源:发表于2017-06-08 17:53 被阅读0次

当一个复杂的对象的构造有许多可选参数的时候,就应该考虑使用构建器(Builder设计模式)来构建对象。

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:>>车身>>>>轮子>>>>座椅>>
    }

相关文章

网友评论

    本文标题:遇到多个构造器参数时考虑使用构建器(Effective Java

    本文链接:https://www.haomeiwen.com/subject/audtqxtx.html