簡單工廠模式透過單一工廠類根據參數決定實例化哪個具體類別,將「創建邏輯」與「使用邏輯」分離。本文以自行車店為例,展示 ES6 Class 實現、介面契約驗證、擴展開放封閉原則的進階寫法。
assemble()、wash()。Speedster、Lowrider、ComfortCruise。BicycleShop.sellBicycle(model) 封裝 switch 創建邏輯。// 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 代碼
new | 簡單工廠 |
|------|---------------------|----------|
| 耦合度 | 高 (客戶端依賴具體類) | 低 (客戶端依賴工廠/介面) |
| 創建邏輯 | 分散在各調用處 | 集中在工廠,易維護、可加日誌/驗證 |
| 擴展性 | 修改所有調用處 | 僅擴展工廠註冊表 |
| 測試性 | 難以 Mock | 易替換工廠實現 |
switch 每加一型別必改工廠代碼 → 用註冊表解決。new 或工廠函數即可,無需正式模式。簡單工廠是設計模式入門第一課,掌握其「封裝變化、面向介面」核心思想,能讓代碼結構更清晰、更易演進。