单例模式
单例模式 vs 全局变量
实现思路
实现代码
let count = 0
const Singleton = (function () {
// 缓存单例实例对象
let instance = null
// 只有首次调用 getInstance 方法时才会用 new 调用 Constructor 方法
// 外部代码无法通过 new 调用 Constructor 创建实例对象
// Contructor 只会执行一次
function Constructor() {
count++
}
function getInstance() {
// 首次调用,创建单例实例并缓存
if (!instance) {
instance = new Constructor()
}
// 之后调用,直接返回缓存的实例对象
return instance
}
// 暴露获取单例对象的方法
return {
getInstance
}
})()
const a = Singleton.getInstance()
const b = Singleton.getInstance()
console.log(a === b) // true
console.log(count) // 1优点
Last updated