美文网首页
单例&多例 模式

单例&多例 模式

作者: erichow | 来源:发表于2016-12-21 13:24 被阅读0次

    只有一个登录用户

    var LoginUser = function(){
      var instance;
      var name;
    
      function LoginUser(name) {
        this.name = name;
      }
      LoginUser.prototype.getName = function() {
        return this.name;
      }
      LoginUser.prototype.setName = function(name) {
        this.name = name;
      }
      return {
        getInstance: function() {
          if (!instance) instance = new LoginUser();
          return instance;
        }
      }
    }();
    

    只有三个登录用户

    var LoginUser = function(){
      var instance = [];
      var count = 0;
      var name;
    
      function LoginUser(name) {
        this.name = name;
      }
      LoginUser.prototype.getName = function() {
        return this.name;
      }
      LoginUser.prototype.setName = function(name) {
        this.name = name;
      }
      return {
        getInstance: function() {
          
          if (instance.length < 3) {
            var user = new LoginUser();
            instance.push(user);
            return user;
          }
          return instance[count++ % 3];
        }
      }
    }();
    

    相关文章

      网友评论

          本文标题:单例&多例 模式

          本文链接:https://www.haomeiwen.com/subject/lekqvttx.html