单例模式确保类唯一实例并提供全局访问,观察者模式实现一对多依赖更新;单例用闭包或静态属性控制实例创建,观察者含Subject和Observer角色,现代开发常用EventBus或框架机制替代。

单例模式确保一个类只有一个实例,并提供全局访问点;观察者模式定义对象间一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都会收到通知并自动更新。
单例模式的实现方式
核心是控制实例创建过程,避免重复生成。常见写法是用闭包或静态属性缓存唯一实例。
- 使用闭包封装私有变量和构造逻辑,返回一个固定对象:
const Singleton = (function() {
let instance;
function createInstance() {
return { data: 'I am the only one' };
}
return {
getInstance() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
// 使用
const a = Singleton.getInstance();
const b = Singleton.getInstance();
console.log(a === b); // true
- ES6 class 写法中,可在类内部用静态属性保存实例,构造函数检查是否已存在:
class Singleton {
static instance = null;
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
this.id = Math.random();
Singleton.instance = this;
}
}
注意:这种方式在严格模式下 new 调用会报错,更稳妥的是把构造设为私有(如抛出错误),只暴露 getInstance 方法。
观察者模式的基本结构
包含两个核心角色:Subject(被观察者,维护订阅者列表并触发通知)和 Observer(观察者,定义接收更新的方法)。
立即学习“Java免费学习笔记(深入)”;
- Subject 类通常有 attach、detach、notify 方法:
class Subject {
constructor() {
this.observers = [];
}
attach(observer) {
if (typeof observer.update === 'function') {
this.observers.push(observer);
}
}
detach(observer) {
this.observers = this.observers.filter(obs => obs !== observer);
}
notify(data) {
this.observers.forEach(observer => observer.update(data));
}
}
- Observer 可以是普通对象,只要实现 update 方法即可:
const observer1 = {
update(data) {
console.log('Observer 1 got:', data);
}
};
const observer2 = {
update(data) {
console.log('Observer 2 got:', data);
}
};
const subject = new Subject();
subject.attach(observer1);
subject.attach(observer2);
subject.notify('Hello from subject!');
现代开发中常使用事件总线(EventBus)、RxJS 的 Observable 或框架内置机制(如 Vue 的 $emit / $on、React 的 Context + useReducer)替代手写观察者,但理解其原理有助于调试和设计解耦逻辑。
两种模式的实际用途
单例适合管理共享资源,比如配置管理器、日志记录器、状态存储(如 Redux store 本质也是单例思想);观察者适合处理松耦合通信场景,如 UI 组件响应数据变化、跨模块消息传递、异步任务完成通知等。
不复杂但容易忽略细节:单例要注意多线程/多实例环境(如 SSR 中模块缓存行为),观察者要注意内存泄漏(及时 detach)和执行顺序问题。











