定義一個創建物件的介面,由子類/實作決定實例化哪個類別。將實例化邏輯延遲到子類,呼叫端無需知悉具體類別,只需傳入型別參數。
var Car = (function() {
var Car = function(model, year, miles) {
this.model = model; this.year = year; this.miles = miles;
};
return function(model, year, miles) {
return new Car(model, year, miles); // 統一回傳實例
};
})();
var tom = new Car("Tom", 2009, 20000);
var dudu = new Car("Dudu", 2010, 5000);
優點:呼叫端可選擇 new Car(...) 或 Car(...),工廠內部統一處理實例化。
var productManager = {};
productManager.createProductA = function() { console.log('ProductA'); };
productManager.createProductB = function() { console.log('ProductB'); };
productManager.factory = function(type) {
return new productManager[type];
};
productManager.factory("createProductA"); // 輸出 ProductA
需求:根據類型動態插入文字、連結、圖片。
var page = page || {};
page.dom = page.dom || {};
// 文字節點
page.dom.Text = function() {
this.insert = function(where) {
where.appendChild(document.createTextNode(this.url));
};
};
// 連結節點
page.dom.Link = function() {
this.insert = function(where) {
var a = document.createElement('a');
a.href = this.url;
a.appendChild(document.createTextNode(this.url));
where.appendChild(a);
};
};
// 圖片節點
page.dom.Image = function() {
this.insert = function(where) {
var img = document.createElement('img');
img.src = this.url;
where.appendChild(img);
};
};
page.dom.factory = function(type) {
return new page.dom[type];
};
var o = page.dom.factory('Link');
o.url = 'https://www.example.com';
o.insert(document.body); // 在 body 末尾插入連結
| 模式 | 核心目的 | 典型回傳 |
|---|---|---|
| 建構函數 | 初始化單一物件實例 | 新實例 (this) |
| 工廠模式 | 封裝建立邏輯,根據參數回傳不同類型實例 | 新實例 (各類型) |
| 單例模式 | 確保全域唯一實例 | 同一實例引用 |
工廠模式在 JavaScript 中極為常見(如 jQuery $()、React createElement、Vue h())。理解其「介面統一、實現隔離」的思想,有助於設計可擴展、可測試的模組架構。