单例&多例 模式

只有一个登录用户

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];
    }
  }
}();

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