Singleton模式
var User = (function() {
var instance;
function _User(){}
_User.prototype.say = function(){}
function init() {
return new _User()
}
return function() {
if( instance == null) {
instance = init();
}
return instance;
}
})();
下面一种模式,可以根据执行的环境,来动态的创建不同的对象
var User = (function() {
var instance;
function _Cat(){}
_Cat.prototype.say = function(){}
function _Dog(){}
_Dog.prototype.say = function(){}
return function() {
if( instance == null) {
if( window.debug ) {
instance = new _Cat();
} else {
instance = new _Dog();
}
}
return instance;
}
})();
// for use
User()