Skip to content

单例模式 ​

单例模式是一个类只有一个实例并提供全局访问。

变量方式 ​

可通过变量保存实例,实例存在时直接返回,否则创建实例并赋值给变量再返回。

js
function Singleton() {
  this.instance = null
}

Singleton.getInstance = function () {
  if (!this.instance) {
    this.instance = new Singleton()
  }
  return this.instance
}

闭包方式 ​

也可通过闭包的方式。

js
function Singleton() {}

Singleton.getInstance = (function () {
  let instance = null
  return function () {
    if (!instance) {
      instance = new Singleton()
    }
    return instance
  }
})()

惰性单例 ​

在需要的时候才创建单例对象。

此例,为创建全局唯一的悬浮登录框,注意把创建 DOM 的职责和管理单例的职责抽离分别放置在两个函数中,以提高复用性。

js
function getSingle(fn) {
  let result
  return function (...args) {
    return result || (result = fn.apply(this, args))
  }
}

function createLoginLayer() {
  const div = document.createElement('div')
  div.innerHTML = '悬浮框'
  div.style.display = 'none'
  document.body.appendChild(div)
  return div
}

const loginBtn = document.getElementById('loginBtn')
const createSingleLoginLayer = getSingle(createLoginLayer)

loginBtn.onclick = function () {
  const loginLayer = createSingleLoginLayer()
  loginLayer.style.display = 'block'
}