单例模式

var singleton = (function() {
  let obj = null
  return function() {
    if (obj) {
      return obj
    }
    // TODO: init obj
    init();
  }
})()

主要应用场景

  • 唯一性明确的场景(比如登录框)

单例工厂

var singletonFactory = (function() {
  let cache = null
  return function(fn) {
    if (cache) {
      return cache
    }
    
    cache = new fn()
  }
})()

function LoginLayer() {
  var domObj = document.createElement('div')
  document.body.appendChild(domObj)
  domObj.style.display = 'none'
  return domObj
}

var getLoginLayerSingleton = singletonFactory(LoginLayer)

btn1.onclick = function() {
  // show
  var loginLayer = getLoginLayerSingleton()
  loginLayer.style.display = 'block'
}

btn1.onclick = function() {
  // hidden
  var loginLayer = getLoginLayerSingleton()
  loginLayer.style.display = 'none'
}

你可能感兴趣的:(单例模式)