JavaScript 设计模式--单例

in JavaScript with 0 comment

JavaScript 设计模式单例模式

单例模式的应用场景是比较广泛的,比如jQuery库、登陆的弹窗、Vuex和Redux中的store、websocket连接、数据库连接池等等

    //用闭包来模拟单例pro,需要手动调用一次
    var closureFun = function() {
      var instance = null;
      return function(item) {
        if(!instance) {
          instance = item
        }
        return instance
      }
    }
    var re = closureFun()
    var result = re([1, 2])
    console.log(result)
    var result1 = re([1, 2, 3])
    console.log(result1)

   //pro max 用立即执行函数,自调用一次
   var closureFun = (function(){
      var instance = null
      return function(item) {
        if(!instance){
          instance = item
        }
        return instance
      }
   })()
   var res = closureFun([1, 2])
   console.log(res)
   var res1 = closureFun([1, 2, 3])
   console.log(res1)

来个简单的demo

var CreateDiv = function (html) {
        this.html = html;
        this.init();
    };
    
    CreateDiv.prototype.init = function () {
        var div = document.createElement('div');
        div.innerHTML = this.html;
        document.body.appendChild(div);
    };
    //用立即执行函数构造一个闭包,hold住instance实例
    var ProxySingletonCreateDiv = (function () {
        var instance;
        return function (html) {
            if (!instance) {
                instance = new CreateDiv(html);
            }
            return instance;
        }
    })();
    
    //var a = new ProxySingletonCreateDiv('sven1');
    var b = new ProxySingletonCreateDiv('sven2');
    var c = new ProxySingletonCreateDiv('sven3');

    console.log(c === b); //true

javascript 模拟静态变量

//javascript模拟静态变量
    var State = (function() {
      var staticValue = {
        initVal: 10
      }
      return {
        get: function(name) {
          return staticValue[name] ? staticValue[name] : null
        }
      }
    })()
   var res = State.get('initVal')
   console.log(res)
评论已关闭.