萬盛學電腦網

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

JavaScript 簡單工廠模式實戰:封裝物件創建邏輯、解耦具體類別依賴

簡單工廠模式透過單一工廠類根據參數決定實例化哪個具體類別,將「創建邏輯」與「使用邏輯」分離。本文以自行車店為例,展示 ES6 Class 實現、介面契約驗證、擴展開放封閉原則的進階寫法。

核心角色

  • Product (產品介面):定義公共行為 assemble()、wash()。
  • ConcreteProduct (具體產品):Speedster、Lowrider、ComfortCruise。
  • Factory (工廠):BicycleShop.sellBicycle(model) 封裝 switch 創建邏輯。

ES6 現代實現

// 1. 產品介面 (用 Class + 靜態方法模擬介面契約)
class Bicycle {
  constructor(model) { this.model = model; }
  assemble() { throw new Error('Must implement assemble()'); }
  wash() { throw new Error('Must implement wash()'); }
  
  // 介面驗證輔助
  static implements(instance) {
    return instance instanceof Bicycle &&
           typeof instance.assemble === 'function' &&
           typeof instance.wash === 'function';
  }
}

// 2. 具體產品
class Speedster extends Bicycle {
  assemble() { console.log('🏎️ 組裝極速車:碳纖車架、窄胎、下把'); }
  wash() { console.log('🧼 清洗極速車:高壓水槍、專用潤滑油'); }
}

class Lowrider extends Bicycle {
  assemble() { console.log('🛴 組裝低騎車:加長前叉、寬把、華麗塗裝'); }
  wash() { console.log('🧼 清洗低騎車:手工打蠟、鍍鉻件拋光'); }
}

class ComfortCruise extends Bicycle {
  assemble() { console.log('🚲 組裝舒適車:人體工學座墊、避震前叉、籃子'); }
  wash() { console.log('🧼 清洗舒適車:泡沫清潔、座墊除菌'); }
}

// 3. 簡單工廠
class BicycleShop {
  static sellBicycle(model) {
    let bicycle;
    switch (model) {
      case 'Speedster': bicycle = new Speedster(model); break;
      case 'Lowrider': bicycle = new Lowrider(model); break;
      case 'ComfortCruise': bicycle = new ComfortCruise(model); break;
      default: throw new Error(`未知車型: ${model}`);
    }
    
    // 契約驗證
    if (!Bicycle.implements(bicycle)) {
      throw new Error('產品未正確實作 Bicycle 介面');
    }
    
    bicycle.assemble();
    bicycle.wash();
    return bicycle;
  }
}

// 使用
const myBike = BicycleShop.sellBicycle('Speedster');
// 輸出:
// 🏎️ 組裝極速車:碳纖車架、窄胎、下把
// 🧼 清洗極速車:高壓水槍、專用潤滑油

進階:可擴展工廠 (開放封閉原則)

新增車型無需修改 BicycleShop 核心代碼,改用註冊表:

class ExtensibleBicycleShop {
  constructor() {
    this.catalog = new Map();
    // 內建車型
    this.register('Speedster', Speedster);
    this.register('Lowrider', Lowrider);
    this.register('ComfortCruise', ComfortCruise);
  }

  register(modelName, Constructor) {
    if (!(Constructor.prototype instanceof Bicycle)) {
      throw new Error('Constructor must extend Bicycle');
    }
    this.catalog.set(modelName, Constructor);
  }

  sellBicycle(model) {
    const Constructor = this.catalog.get(model);
    if (!Constructor) throw new Error(`未知車型: ${model}`);
    const bicycle = new Constructor(model);
    bicycle.assemble();
    bicycle.wash();
    return bicycle;
  }
}

// 客戶端動態擴展
const shop = new ExtensibleBicycleShop();
shop.register('E-Bike', class extends Bicycle {
  assemble() { console.log('⚡ 組裝電輔車:馬達、電池、控制器'); }
  wash() { console.log('🧼 清洗電輔車:避開電池艙、低壓水'); }
});

shop.sellBicycle('E-Bike'); // 無需修改 Shop 代碼

工廠模式 vs 直接 new

| 維度 | 直接 new | 簡單工廠 | |------|---------------------|----------| | 耦合度 | 高 (客戶端依賴具體類) | 低 (客戶端依賴工廠/介面) | | 創建邏輯 | 分散在各調用處 | 集中在工廠,易維護、可加日誌/驗證 | | 擴展性 | 修改所有調用處 | 僅擴展工廠註冊表 | | 測試性 | 難以 Mock | 易替換工廠實現 |

適用場景

  • 物件創建邏輯複雜(需配置、依賴注入、狀態初始化)。
  • 同一介面有多種實現,運行時根據條件決定(如支付渠道:Alipay/WeChat/Stripe)。
  • 框架/庫提供擴展點,讓使用者註冊自定義實現。

注意事項

  • 違反開放封閉原則:傳統 switch 每加一型別必改工廠代碼 → 用註冊表解決。
  • 單一職責:工廠只負責創建,業務邏輯勿混入。
  • 非萬能:單純資料物件 (DTO/VO) 直接 new 或工廠函數即可,無需正式模式。

簡單工廠是設計模式入門第一課,掌握其「封裝變化、面向介面」核心思想,能讓代碼結構更清晰、更易演進。

copyright © 萬盛學電腦網 all rights reserved