vendredi 28 août 2015

Why is the factory method declared as protected?

I'm reading the Head First Design Patterns book and on the "Declaring a factory method" section in Chapter 4, the method is declared as protected:

public abstract class PizzaStore {

    public Pizza orderPizza(String type) {
        Pizza pizza;
        pizza = createPizza(type);
        pizza.prepare(); // other methods follow

        return pizza;
    }

    protected abstract class Pizza createPizza(String type);

}

This confuses me because I initially thought, in fact it is also stated in the book, that having a factory (method) allows you to have a single place that creates an instance for you, not just for acting on later but also for "querying". By "acting on" I mean pizza.cut() etc, and by "querying" I mean pizza.isSpicy().

Wouldn't the protected keyword limit the querying to only the subclasses and same-package classes? What if a 3rd-party class needed to know that the pizza is spicy before ordering?

I may be overthinking this, because the highlight box does not say it HAS to be protected but it's there in the sample code.

Aucun commentaire:

Enregistrer un commentaire