萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

深入理解 JavaScript 設計模式:工廠模式詳解與多種實作範例

工廠模式核心定義

定義一個創建物件的介面,由子類/實作決定實例化哪個類別。將實例化邏輯延遲到子類,呼叫端無需知悉具體類別,只需傳入型別參數。

範例一:簡易工廠函式(隱藏 new)

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

範例三:DOM 元素動態建構工廠(實戰場景)

需求:根據類型動態插入文字、連結、圖片。

步驟 1:定義具體建造者(子類)

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);
  };
};

步驟 2:定義工廠方法

page.dom.factory = function(type) {
  return new page.dom[type];
};

步驟 3:使用工廠建立並插入

var o = page.dom.factory('Link');
o.url = 'https://www.example.com';
o.insert(document.body); // 在 body 末尾插入連結

工廠模式適用場景

  • 物件建立過程複雜(依賴設定檔、環境變數、多步驟初始化)。
  • 需根據運行時參數決定具體實現類別(如不同付款方式、不同儲存驅動)。
  • 希望呼叫端與具體類別解耦,便於測試與替換實現。

工廠 vs 建構函數 vs 單例

模式核心目的典型回傳
建構函數初始化單一物件實例新實例 (this)
工廠模式封裝建立邏輯,根據參數回傳不同類型實例新實例 (各類型)
單例模式確保全域唯一實例同一實例引用

工廠模式在 JavaScript 中極為常見(如 jQuery $()、React createElement、Vue h())。理解其「介面統一、實現隔離」的思想,有助於設計可擴展、可測試的模組架構。

copyright © 萬盛學電腦網 all rights reserved