进阶技巧
JavaScript 设计模式
单例/观察者/发布订阅、模块模式、策略模式 JS 实现
JavaScript 设计模式
设计模式在 JS 中有独特的实现——闭包代替代 private、高阶函数替代策略、事件总线替代观察者。
学完本章你将: 掌握单例/观察者/发布订阅、模块模式、策略模式 JS 实现。
单例模式
javascript
// 闭包实现
const createSingleton = (factory) => {
let instance;
return (...args) => instance ??= factory(...args);
};
const getDB = createSingleton((url) => ({ url, connect: () => {} }));
const db1 = getDB("postgres://...");
const db2 = getDB("mysql://..."); // 还是 db1
console.log(db1 === db2); // true
发布订阅(EventBus)
javascript
class EventBus {
#handlers = new Map();
on(event, handler) {
if (!this.#handlers.has(event)) this.#handlers.set(event, []);
this.#handlers.get(event).push(handler);
}
emit(event, data) {
this.#handlers.get(event)?.forEach(h => h(data));
}
off(event, handler) {
const handlers = this.#handlers.get(event);
if (handlers) this.#handlers.set(event, handlers.filter(h => h !== handler));
}
}
策略模式(函数版)
javascript
const paymentStrategies = {
alipay: (amount) => { /* 支付宝支付 */ },
wechat: (amount) => { /* 微信支付 */ },
credit: (amount) => { /* 信用卡支付 */ },
};
function checkout(amount, method) {
const strategy = paymentStrategies[method];
if (!strategy) throw new Error(`不支持 ${method}`);
return strategy(amount);
}
checkout(100, "alipay");