单例模式

148 阅读1分钟

单例模式

function Singleton(){
  this.data = 'singleton';
}
// 这里应用了闭包
Singleton.getInstance = (function () {
  var instance;
  return function(){
    if (!instance) instance = new Singleton();
    return instance;
  }
})();

var sa = Singleton.getInstance();
var sb = Singleton.getInstance();
console.log(sa === sb); // true
console.log(sa.data); // 'singleton'

es6写法

class Singleton {
    constructor(){
        this.data = 'singleton'
    }
    
    static getInstance () {
        if(!Singleton.instance){
            Singleton.instance = new Singleton()
        }
        return Singleton.instance
    }
}

应用场景: 全局唯一消息框

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <style>
      .modle {
        width: 30vw;
        height: 30vh;
        border: 1px solid greenyellow;
        text-align: center;
        line-height: 30vh;
      }
    </style>
  </head>

  <body>
    <h3>单例模式之唯一弹框</h3>
    <div id="btn">点我</div>
  </body>

  <script>
    function single(fn) {
      let o;
      return function () {
        if (!o) o = fn.apply(this, arguments);
        return o;
      };
    }

    function creatModle() {
      let div = document.createElement("div");
      div.innerHTML = "我是登录弹框";
      div.className = "modle";
      div.style.display = "none";
      document.body.appendChild(div);
      return div;
    }

    let creatOnlyOnce = single(creatModle);

    document.getElementById("btn").onclick = function () {
      let m = creatOnlyOnce();
      m.style.display = "block";
    };
  </script>
</html>

Edit 唯一弹框