
设计模式是解决常见编程问题的可复用方案,本文介绍几个在 JavaScript 中常用的设计模式。
单例模式
确保一个类只有一个实例:
class Singleton {
static instance;
constructor() {
if (Singleton.instance) return Singleton.instance;
Singleton.instance = this;
}
}
观察者模式
定义对象间的一对多依赖关系:
class EventEmitter {
constructor() {
this.events = {};
}
on(event, fn) {
(this.events[event] ||= []).push(fn);
}
emit(event, ...args) {
this.events[event]?.forEach((fn) => fn(...args));
}
}
策略模式
定义一系列算法,使它们可以相互替换。



