如何使用具有多个构建参数的继承的构建器?

时间:2019-04-14 12:29:36

标签: java inheritance

我正在尝试将构建器模式与一个简单的抽象构建器一起使用,我稍后需要扩展...类似这样的东西...

public abstract class Pizza {

    private Topic topic;
    public enum Topic {
        Cheese, Pinneaple, Tomato, Ham
    }

    Pizza(Builder<?> topic) {  
        this.topic = topic.topic;
    }

    abstract static class Builder<T extends Builder<T>> {

        private Topic topic;

        Builder withTopic(Topic topic) {
            this.topic = topic;
            return self();
        }

        abstract Pizza build();

        protected abstract T self();

    }

    public Topic getTopic() {
        return topic;
    }
}

然后我在这样的类中实现

public class NyPizza extends Pizza {

    private final int numberOfSlices;


    public static class Builder extends Pizza.Builder {
        private int numberOfSlices;

        Builder withNumberOfSlices(int slices) {
            this.numberOfSlices = slices;
            return this;
        }

        @Override
        public NyPizza build() {
            return new NyPizza(this);
        }


        @Override
        protected Pizza.Builder self() {
            return this;
        }

    }

    private NyPizza(Builder builder) {
        super(builder);
        this.numberOfSlices = builder.numberOfSlices;
    }

    public int getNumberOfSlices() {
        return numberOfSlices;
    }
}

现在来了有趣的部分...

当我这样做

NyPizza nyPizza = new NyPizza.Builder().withNumberOfSlices(3).build();

我从NyPizza得到一个实例

但是当我做

NyPizza nyPizza = new NyPizza.Builder().withNumberOfSlices(3).withTopic(Pizza.Topic.Cheese).build();

由于构建器返回的是Pizza而不是NyPizza的实例,因此出现了错误。

我做错了什么?我正在尝试使用NyPizza作为我从Pizza扩展的生成器,但不确定是否可以...

0 个答案:

没有答案