用控制台实现单例模式
在 JavaScript 中,可以使用闭包来实现单例模式。下面是一个示例:
let 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;
}
};
})();
// 使用方式
let instance1 = Singleton.getInstance();
let instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
在这个示例中,Singleton 是一个立即执行函数,里面定义了 instance 和 createInstance 两个函数。createInstance 函数用于创建单例实例,而 getInstance 函数则用于获取单例实例。
当第一次调用 getInstance 时,会检查 instance 是否已经存在。如果不存在,就调用 createInstance 函数创建实例,然后将其保存在 instance 中。如果已经存在,就直接返回 instance。
由于 instance 是在闭包中定义的,所以它只能在 getInstance 函数内部访问。这就保证了整个应用程序中只有一个实例。
原文地址: http://www.cveoy.top/t/topic/0dw 著作权归作者所有。请勿转载和采集!