单例模式

来源:互联网 发布:周末父母 知乎 编辑:程序博客网 时间:2024/06/06 00:20
//模块模式。为单例创建私有变量和特权方法。
    var singleton = function(){
    //私有变量和私有函数
    var privateVariable = 10;
    function privateFunction(){
    return false;
    }
    //特权/公有方法和属性
    return {
    publicProperty:true,
    publicMethod:function(){
    privateVariable++;
    return priviteFunction();
    }
    };
    }();


    //增强的模块模式。
    var application = function(){
    //私有变量和函数
    var components = new Array();
    //初始化
    components.push(new BaseComponent());
    //创建application的一个局部副本
    var app = new BaseComponent();
    //公共接口
    app.getComponentCount = function(){
    return components.length;
    };
    app.registerComponent = function(component){
    if(typeof component == 'object'){
    components.push(component);
    }
    };
    //返回这个副本
    return app;
    }();
0 0
原创粉丝点击