JavaScript设计模式(一):单例模式

226 阅读1分钟

定义

单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
这个可以类比浏览器中的 window 对象。有两个点需要注意:

  • 全局只有一个实例
  • 全局访问点唯一

简单来说就是,有个唯一的全局对象,供我们全局访问使用。

实现

const mySingleton = function (name) {
  this.name = name
  this.instance = null
}
mySingleton.prototype.getName = function () {
  return this.name
}
mySingleton.getInstance = function (name) {
  if (!this.instance) {
    this.instance = new mySingleton(name)
  }
  return this.instance
}
const a = mySingleton.getInstance('qi')
const b = mySingleton.getInstance('7')
console.log(a.getName(), b.getName()) // qi qi
console.log(a === b) // true

适用场景

主要用于维护一个全局实例对象,减少频繁创建和销毁实例以及内存的占用。如:弹窗,第三方库等。

if (window.libName) {
    return window.libName 
} else {
    window.libName = '...'
}


参考文章:
JavaScript 设计模式(一):单例模式