开发者

Builder pattern for constructing an instance of a class that can have different types

Consider the following product and AbstractBuilder from wikipedia:

/** "Product" */
class Pizza {
        private String dough = "";
        private String sauce = "";
        private String topping = "";

        public void setDough(String dough) {
                this.dough = dough;
        }

        public void setSauce(String sauce) {
                this.sauce = sauce;
        }

        public void setTopping(String topping) {
                this.topping = topping;
        }
}

/** "Abstract Builder" */
abstract class PizzaBuilder {
        protected Pizza pizza;

        public Pizza getPizza() {
                return pizza;
        }

        public void createNewPizzaProduct() {
                pizza = new Pizza();
        }

        public abstract void buildDough();

        public abstract void buildSauce();

        public abstract void buildTopping();
}

If you see the method createNewPizzaProduct in class PizzaBuilder.

If Pizza i开发者_如何转开发mplemented an interface, say Foo and had to implement a method bar, how would the method createNewPizzaProduct account for this since there would be many different types of Pizza?

What would be the most elegant solution such that the pattern is not violated? This pattern is new to me.


createNewPizzaProduct would not have to care whether the Pizza class implements specific methods: its sole responsibility is to instantiate a Pizza. If you're asking how it would deal with the possibility of having to create different Pizza implementations based on some criterion, then you'll want to look into the Factory pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜