簡單工廠模式解決的是一個很具體的問題:我想依某個參數取得一個物件,但不希望每個呼叫點都寫滿 if-else 決定該 new 哪一個。把這段決策集中到一個函式裡,就是工廠。
<!DOCTYPE html>
<html>
<head><title>簡單工廠模式</title></head>
<body>
<script>
// 簡單工廠模式
var BicycleShop = function () {};
BicycleShop.prototype = {
sellBicycle: function (model) {
var bicycle = null;
switch (model) {
case 'The Speedster':
bicycle = new Speedster(); break;
case 'The Lowrider':
bicycle = new Lowride(); break;
case 'The Comfort Cruiser':
bicycle = new ComfortCruise(); break;
}
Interface.ensureImplements(bicycle, Bicycle);
bicycle.assemble();
bicycle.wash();
return bicycle;
}
};
var AcmeBicycleShop = function () {};
extend(AcmeBicycleShop, BicycleShop);
AcmeBicycleShop.prototype.createBicycle = function (model) {
var bicycle = null;
switch (model) {
case 'The Speedster': bicycle = new AcmeSpeedster(); break;
case 'The Lowrider': bicycle = new AcmeLowrider(); break;
case 'The Flatlander': bicycle = new AcmeFlatlander(); break;
case 'The Comfort Cruiser':
default: bicycle = new AcmeComfortCruiser();
}
Interface.ensureImplements(bicycle, Bicycle);
return bicycle;
};
// 工廠模式適用於:依參數不同而建立不同物件的情境
</script>
</body>
</html>
兩個賣場(BicycleShop 與 AcmeBicycleShop)都負責「賣腳踏車」,但實際產出的車款不同。呼叫端只知道 sellBicycle('The Speedster'),不必知道背後 new 的是哪一個類別——這就是工廠最大的價值:把「選擇哪個實作」這件事收斂到一處。
Interface.ensureImplements 是《Head First 設計模式》裡的做法,用來在執行期確認物件有沒有實作該有的方法,模擬 Java 的介面約束。
用對照表取代 switch。新增車款時不必再改條件分支:
var BICYCLES = {
'The Speedster': Speedster,
'The Lowrider': Lowride,
'The Comfort Cruiser': ComfortCruise
};
function createBicycle(model) {
var Ctor = BICYCLES[model] || ComfortCruise; // 預設值
return new Ctor();
}
原範例有幾個拼字不一致。'The Speedster' 與 'The speedster'、Lowride 與 Lowrider,這類大小寫與拼寫落差會讓 switch 靜默地走到 default。實務上建議把 model 當成枚舉常數,而不是自由字串。
extend 的實作方向要注意。範例呼叫 extend(AcmeBicycleShop, BicycleShop),但一般慣例是 extend(子, 父) 才對;若沿用 jQuery 的 $.extend 語意,參數順序恰好相反,很容易搞混。ES6 之後直接寫 class AcmeBicycleShop extends BicycleShop 就沒有這個歧義了。
嚴格說來,上面這個是「簡單工廠」(也稱靜態工廠),它是一個函式,不是 GoF 二十三種模式之一。真正的 Factory Method 是把建立物件的步驟延後到子類別,讓子類別決定要實例化哪一個類別——範例中 AcmeBicycleShop 覆寫 createBicycle 的做法,其實已經偏向 Factory Method 的思路了。理解這個區分,能幫你在設計時判斷:需要抽的是「一個函式」,還是「一整條繼承鏈」。
最後記得:工廠模式的代價是多了一層間接。當產品只有兩三種、建立邏輯又不複雜時,直接 new 反而更誠實。