mercredi 2 mai 2018

How would PizzaStore accept different factories when depending on SimplePizzaFactory?

When I'm reading factory pattern of Head First Design Patterns, I'm confused when reading the simple factory part. Here is the class diagram. enter image description here

PizzaStore code:

 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;
  }
// other methods here
}

code for SimplePizzaFactory

public class SimplePizzaFactory {

  public Pizza createPizza(String type) {
    Pizza pizza = null;
    if (type.equals("cheese")) {
      pizza = new CheesePizza();
    } else if (type.equals("pepperoni")) {
      pizza = new PepperoniPizza();
    } else if (type.equals("clam")) {
      pizza = new ClamPizza();
    } else if (type.equals("veggie")) {
      pizza = new VeggiePizza();
    }
    return pizza; 
  }
}

in Franchising the pizza store part, it says:

If we take out SimplePizzaFactory and create three different factories, NYPizzaFactory, ChicagoPizzaFactory and CaliforniaPizzaFactory, then we can just compose the PizzaStore with the appropriate factory and a franchise is good to go.

in code,

NYPizzaFactory nyFactory = new NYPizzaFactory();
PizzaStore nyStore = new PizzaStore(nyFactory);
nyStore.order(“Veggie”);

ChicagoPizzaFactory chicagoFactory = new ChicagoPizzaFactory();
PizzaStore chicagoStore = new PizzaStore(chicagoFactory);
chicagoStore.order(“Veggie”);

My questions is, PizzaStore has a dependency on a concret class, which is SimplePizzaFactory, how can we new a PizzaStore with NYPizzaFactory instance or ChicagoPizzaFactory instance?

Aucun commentaire:

Enregistrer un commentaire