初面网初面网

单例模式

单例,保证一个类仅有一个实例,并提供一个访问它的全局访问点。

主要解决一个全局使用的类频繁地创建和销毁,占用内存。

  • ES5版

使用闭包实现

var Singleton = (function(){
  var instance

  function User(name, age){
    this.name = name
    this.age = age
  }

  return function(name, age){
    if(!instance){
      // 创建实例
      instance = new User(name,age)
    }
    return instance
  }
})
  • ES6版
class Singleton{
  constructor(name, age){
    if(!Singleton.instance){
      this.name = name
      this.age = age
      Singleton.instance = this
    }
    return Singleton.instance
  }
}

new Singleton("tom", 18) === new Singleton("tony",33)

小例子

一个弹出提示框

/*
  css部分
  .the-modal{
    position: fixed;
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background-color: yellow;
  }
*/

// html部分
/*
<button id="open">打开</button>
<button id="close">关闭</button>
*/

// js部分
const Modal = (function(){
  let instance = null
  return function(){
    if(!instance){
      instance = document.createElement("div")
      instance.innerHTML = "登录对话框"
      instance.className = "the-modal"
      instance.style.display = "none"
      document.body.appendChild(instance)
    }
    return instance;
  }
})()

document.querySelector("#open").onclick = function(){
  const modal = Modal()

  modal.style.display = "block"
}

document.querySelector("#close").onclick = function(){
  const modal = Modal()

  modal.style.display = "none"
}

更新于 2025/2/26