javascript之设计模式一(单例模式)

一般针对不同的企业都用自己封装的前端自定义功能模块

百度,雅虎等大企业都有自己封装的单例模式

下面主要讲单例模式的三大模块:命名空间,私有静态变量,功能模块化

示例如下:

//1.单例模式之设置私有静态变量,防篡改受保护
var Dog = (function(){
    var dog = {
        age:3,
        color:'white',
        sex:'m'
    };
    return {
        get : function(name){
            return dog[name]?dog[name]:null;
        }
    }
})();
var dogage = Dog.get('age');
console.log(dogage);
//2.单例模式之命名空间,可以代码模块复用命名空间
var Ping = {
    GetId : function(id){
        return document.getElementById(id);
    },
    css : function(id,key,value){
        return Ping.GetId(id).style[key] = value;
//return this.GetId(id).style[key] = value;
    }
}
Ping.css('fgg',"color","blue");
//3.单例模式之功能模块化,针对不同功能自定义系统化
    var Common = {
        Ajax : {
            aget:function(){},
            apost:function(){}
        },
        Util : {
            util_method1 : function(){
                console.log(111);
            },
            util_method2 : function(){
            }
        },
        Tool : {
            tool_validate:function(){  
            },
            tool_search:function(){
               //... 
            }
        }    
    }
    Common.Util.util_method1();

 单例模式之利:它对代码的组织作用,把相关的方法属性组织在一个不会被多次实例话的单体里面,更方便代码的维护成本,防止误改代码。

 单例模式之弊:它提供的是一种单点访问,有可能导致模块间的强耦合,所以不利于单元测试,是故后期可以用一个真正的对象工厂来代替分支型单体。

猜你喜欢

转载自www.cnblogs.com/b-code/p/9141625.html
今日推荐