先來看一下工廠模式的特性吧~
後面沿用上篇的Pizza Store來詳細說明
PizzaFactory()
Pizza()
假設我們在美國開了Pizza連鎖店,而且生意比達X樂好,不同分店會因為所在的地區口味去調整生產方式,代表我們不能讓所有披薩都從同一間工廠出產。
如果不會物件導向跟設計模式的話,我們可能會寫出以下超爆巢狀迴圈而且會生出很多concrete class的程式:
public class DependentPizzaStore {
public Pizza createPizza(String style, String type) {
Pizza pizza = null;
if (style.equals(“NY”)) {
//紐約的Pizza有不同口味
if (type.equals(“cheese”)) {
pizza = new NYStyleCheesePizza();
}
else if (type.equals(“veggie”)) {
pizza = new NYStyleVeggiePizza();
}
else if (type.equals(“clam”)) {
pizza = new NYStyleClamPizza();
}
else if (type.equals(“pepperoni”)) {
pizza = new NYStylePepperoniPizza();
}
}
else if (style.equals(“Chicago”)) {
//芝加哥的Pizza有不同口味
if (type.equals(“cheese”)) {
pizza = new ChicagoStyleCheesePizza();
}
else if (type.equals(“veggie”)) {
pizza = new ChicagoStyleVeggiePizza();
}
else if (type.equals(“clam”)) {
pizza = new ChicagoStyleClamPizza();
}
else if (type.equals(“pepperoni”)) {
pizza = new ChicagoStylePepperoniPizza();
}
}
else {
System.out.println(“Error: invalid type of pizza”);
return null;
}
pizza.bake();
pizza.cut();
pizza.box();
return pizza;
}
}
}
所以我們還是好好運用工廠模式來完成吧!
這邊會有三個抽象類別:
Pizza()
IngredientFactory()
PizzaFactory()
首先是供應食材的工廠 IngredientFactory()
public interface IngredientFactory {
public Dough createDough();
public Sauce createSauce();
public Cheese createCheese();
public Seafood createSeafood();
public Veggies createVeggies();
}
接著定義Pizza的抽象類別
public abstract class Pizza{
//只會使用特定工廠出產的食材
public String name;
public Dough dough;
public Seafood seafood;
public Veggies veggies;
public Sauce sauce;
//會在子類別實現不同的pizza作法
abstract void prepare();
void setName(String name){
this.name = name;
}
void getName(){
System.out.println(this.name);
}
void bake(){
System.out.println("Bake for 30 mins");
}
void cut(){
System.out.println("Cut into 8 slices");
}
void box(){
System.out.println("Place the pizza in a proper box");
}
}
下一篇會講解要如何把這些抽象類別實現,去配合不同的pizza店跟不同工廠的生產 →
Disclaimer
因為讀的是原文版,所以難免會有翻譯詞不達意或是專有名詞上的差異,有錯誤的話歡迎在留言區一起交流!