2)Javascript设计模式:Singleton模式

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()
posted @ 2015-12-26 18:09  sexy_girl  阅读(237)  评论(0编辑  收藏  举报