I know there are hundreds of questions about this on here. I've probably read fifty different questions, blog posts and textbooks. The problem is I've gotten about 75 different answers. I have seen all of the following described as some type of factory, and I can't follow the muddled terminology, and get confused on the pros and cons.
public class PizzaFactory {
public static Pizza(String city) {
switch(city) {
case "Chicago": return new DeepDishPizza();
case "New York": return new ThinCrustPizza();
}
}
}
vs
public abstract class PizzaFactory {
public Pizza getPizza();
}
public class ChicagoPizzaShop extends PizzaFactory {
public Pizza getPizza() {
return new DeepDishPizza();
}
}
public class NewYorkPizzaShop extends PizzaFactory {
public Pizza getPizza() {
return new ThinCrustPizza();
}
}
public class SomeOtherClass {
public Pizza getPizza(String city) {
PizzaFactory pizzaShop;
switch(city) {
case "Chicago": pizzaShop = new ChicagoPizzaShop();
break;
case "New York" : pizzaShop = new NewYorkPizzaShop();
break;
return pizzaShop.getPizza();
}
}
}
vs
public class PizzaFactoryFactory {
public abstract class PizzaFactory {
public Pizza getPizza();
}
public class ChicagoPizzaShop extends PizzaFactory {
public Pizza getPizza() {
return new DeepDishPizza();
}
}
public class NewYorkPizzaShop extends PizzaFactory {
public Pizza getPizza() {
return new ThinCrustPizza();
}
}
public Pizza getPizza(String city) {
switch (city) {
case "Chicago": return new ChicagoPizzaShop().getPizza();
case "New York": return new NewYorkPizzaShop().getPizza();
}
}
}
vs
public abstract class PizzaFactory {
public Pizza getPizza();
}
public class ChicagoPizzaShop extends PizzaFactory {
public Pizza getPizza() {
return new DeepDishPizza();
}
}
public class NewYorkPizzaShop extends PizzaFactory {
public Pizza getPizza() {
return new ThinCrustPizza();
}
}
}
public abstract Customer {
public Pizza orderPizza();
}
public ChicagoCustomer extends Customer {
public Pizza orderPizza() {
return new ChicagoPizzaShop.getPizza();
}
}
public NewYorkCustomer extends Customer {
public Pizza orderPizza() {
return new NewYorkPizzaShop.getPizza();
}
}
// How does one choose which Customer to use? *Another* factory?
There are probably others I'm not thinking of right now. Which, if any, of these is an Abstract Factory pattern? The Factory Method pattern? Some other thing? More concretely, I have eight different subclasses of an abstract class, and I need to return one of those based on a user selection which I can represent either as a string, an int, or an enum. How to best go about it?