mercredi 20 septembre 2017

Difference between composing Factory and inheriting

I'm reading about "Factory method" design pattern from "Head First Design Patterns". So, there is a class

public class PizzaStore {
    SimplePizzaFactory factory;
    public PizzaStore(SimplePizzaFactory factory) {
        this.factory = factory;
    }
    public Pizza orderPizza(String type) {
        Pizza pizza;
        pizza = factory.createPizza(type);
        pizza.prepare();
        pizza.bake();
        pizza.cut();
        pizza.box();
        return pizza;
    }
}

As you can see above, we store factory and then call createPizza(String) virtual function and this will call appropriate createPizza(...) function for the concrete factory class, e.g., NYStylePizzaFactory or ChicagoStylePizzaFactory. But then author continues:

But you’d like a little more quality control...!

and does the following changes in the code:

public abstract class PizzaStore {
    public Pizza orderPizza(String type) {
        Pizza pizza;
        pizza = createPizza();
        pizza.prepare();
        pizza.bake();
        pizza.cut();
        pizza.box();
        return pizza;
    }
    abstract Pizza createPizza();
}

public class NYStylePizzaStore : PizzaStore {
    Pizza createPizza() {
        return new NYStylePizza();
    }
}

public class ChicagoStylePizzaStore : PizzaStore {
    Pizza createPizza() {
        return new ChicagoStylePizza();
    }
}

So, I don't understand why we gain more quality control in this case? It seems that the result is the same - appropriate virtual function is called.

Aucun commentaire:

Enregistrer un commentaire