簡單工廠又稱為靜態工廠模式,但它並不是設計模式!它更像是一種開發的慣用方式。
假設今天我們到pizza店去點pizza,大概會是:
public class PizzaStore {
public Pizza orderPizza(String orderType){
Pizza pizza;
//需要隨著pizza口味增加而去改寫這邊的程式碼
if(orderType.equals("hawaii")){
pizza = new Hawaii();
}
else if(orderType.equals("pepperoni")){
pizza = new Pepperoni();
}
else{
pizza = new Seafood();
}
pizza.bake();
pizza.cut();
pizza.box();
return pizza;
}
}
上一篇有提過可以把其中包含不同pizza的if-else判斷式拉出來寫成PizzaFactory()
:
public class PizzaFactory {
Pizza pizza;
public Pizza createPizza(String orderType){
if(orderType.equals("hawaii")){
pizza = new Hawaii();
}
else if(orderType.equals("pepperoni")){
pizza = new Pepperoni();
}
else{
pizza = new Seafood();
}
return pizza;
}
}
public class PizzaStore {
PizzaFactory pizzaFactory;
public PizzaStore(PizzaFactory pizzaFactory){
this.pizzaFactory = pizzaFactory;
}
public Pizza orderPizza(String orderType){
//由pizza工廠去創造物件細節,這邊只要負責點餐的部分
Pizza pizza = pizzaFactory.createPizza(orderType);
pizza.bake();
pizza.cut();
pizza.box();
return pizza;
}
}
簡單工廠模式的特色就是會把創造物件的細節獨立出來放到工廠中,我們只要負責接收它回傳的物件就好。
Disclaimer
因為讀的是原文版,所以難免會有翻譯詞不達意或是專有名詞上的差異,有錯誤的話歡迎在留言區一起交流!