This question already has an answer here:
- What are the differences between Abstract Factory and Factory design patterns? 16 answers
I have read about Factory Method where Sub class creates needed Object and Abstract Factory has methods where concrete classes creates needed Object
Factory Method
public class PizzaStore {
public Pizza orderPizza(String type) {
Pizza pizza = createPizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
}
abstract Pizza createPizza(String type);
}
public NewYorkPizzaStore extends PizzaStore {
public Pizza createPizza(String type) {
Pizza pizza = null;
if("cheese".equals(type)) {
pizza = new CheesePizza();
}
else if("onion".equals(type)) {
pizza = new OnionPizza();
}
return pizza;
}
}
public class pizzaTestDriveByFactoryMethod() {
public static void main(String args[]) {
PizzaStore ps = new NewYorkPizzaStore();
ps.orderPizza("cheese");
}
}
Using a Factory
public class NewYorkPizzaFactory extends PizzaFactory {
public Pizza createPizza(String pizza) {
Pizza pizza = null;
if("cheese".equals(type)) {
pizza = new CheesePizza();
} else if("onion".equals(type)) {
pizza = new OnionPizza();
}
return pizza;
}
}
public class PizzaStore {
PizzaFactory factory;
public PizzaStore(PizzaFactory factory) {
this.factory = factory
}
public Pizza orderPizza(String type) {
Pizza pizza = factory.createPizza(type)
pizza.prepare();
pizza.bake();
pizza.cut();
return pizza;
}
}
public class pizzaTestDriveByAbstractFactory() {
public static void main(String args[]) {
PizzaFactory nwFactory = new NewYorkPizzaFactory();
PizzaStore ps = new PizzaStore(nwFactory);
ps.orderPizza("cheese");
}
}
Same use case implemented using Factory Method and Abstract Factory. Why there should be a FactoryMethod instead of using Abstract Factory or a Utility Factory (Such as Chicago Factory/NewYorkFactory). In which case Factory method is useful on Abstract Method?