JavaScript 設計模式應用
設計模式不是銀彈,但它是「經過驗證的解決方案」,能讓團隊溝通更有效率。
Observer 模式
class EventEmitter {
#listeners = new Map();
on(event, fn) {
if (!this.#listeners.has(event)) this.#listeners.set(event, []);
this.#listeners.get(event).push(fn);
}
emit(event, ...args) {
this.#listeners.get(event)?.forEach(fn => fn(...args));
}
}
Strategy 模式
const paymentStrategies = {
creditCard: (amount) => `刷卡付款 ${amount} 元`,
linePay: (amount) => `LINE Pay 付款 ${amount} 元`,
bankTransfer: (amount) => `轉帳付款 ${amount} 元`,
};
function pay(method, amount) {
return paymentStrategies[method](amount);
}
Module 模式
const Counter = (() => {
let count = 0;
return {
increment: () => ++count,
getCount: () => count,
};
})();
何時不該用模式
- 專案規模小,模式反而增加複雜度
- 只是為了「用模式」而用
- 語言本身已內建支援