Mark24
记录灵感、技术、思考
单例模式JavaScript具体实现
立即执行函数
const Singleton = (function () {
let instance;
function createInstance() {
let 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 Class
class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
}
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true
Proxy方式
class Person {
constructor() {
this.name = "tom"
}
}
const Singleton = new Proxy(Person, {
// construct
// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy/construct
construct(target, args) {
// target 是 Person 类
// args 是代理的参数
// console.log(`Creating a ${target.name}`);
// Expected output: "Creating a Person"
if (target.instance == undefined) {
target.instance = new target(...args);
}
return target.instance;
}
})
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true
console.log(instance1.name); // tom
console.log(instance2.name); // tom