js 实现单例模式
使用模块模式实现单例
在JavaScript中,模块模式是常见的单例实现方式。通过闭包和立即执行函数表达式(IIFE)创建私有作用域,确保单例的唯一性。
const Singleton = (function() {
let instance;
function createInstance() {
const object = new Object('I am the instance');
return object;
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
使用ES6类实现单例
ES6的class语法可以通过静态属性和方法实现单例模式。静态属性存储唯一实例,静态方法控制实例化过程。

class Singleton {
static instance;
constructor() {
if (Singleton.instance) {
return Singleton.instance;
}
Singleton.instance = this;
}
}
const obj1 = new Singleton();
const obj2 = new Singleton();
console.log(obj1 === obj2); // true
使用对象字面量实现单例
最简单的单例实现方式是直接使用对象字面量。JavaScript对象本身就是单例,无需特殊处理。

const singleton = {
property: 'value',
method: function() {
console.log('Method called');
}
};
Object.freeze(singleton); // 防止修改
使用Proxy实现单例
Proxy可以拦截实例化操作,确保只创建一个实例。这种方式适合需要控制实例化过程的场景。
class SingletonClass {
constructor() {
this.property = 'value';
}
}
const SingletonProxy = new Proxy(SingletonClass, {
instance: null,
construct(target, args) {
if (!this.instance) {
this.instance = new target(...args);
}
return this.instance;
}
});
const proxy1 = new SingletonProxy();
const proxy2 = new SingletonProxy();
console.log(proxy1 === proxy2); // true
惰性单例实现
惰性单例延迟实例化直到第一次使用时才创建实例。这种方式优化了资源使用。
const LazySingleton = (function() {
let instance = null;
function init() {
return {
random: Math.random()
};
}
return {
getInstance: function() {
if (!instance) {
instance = init();
}
return instance;
}
};
})();
console.log(LazySingleton.getInstance().random === LazySingleton.getInstance().random); // true
每种实现方式适用于不同场景,模块模式适合需要私有变量的情况,ES6类方式更符合现代JavaScript风格,对象字面量最简单,Proxy方式最灵活,惰性单例优化性能。






