单例&多例 模式
2016-12-21 本文已影响0人
erichow
只有一个登录用户
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];
}
}
}();