设计模式学习-(7. 单例模式)

// 命名空间

var Zxf = {
        g : function ( id ) {
            return document.getElementById( id );
        },
        css : function ( id , key , value ) {
            var dom = typeof id ==='string' ? this.g( id ) : id
            dom.style[key] = value;
        }
    };
    Zxf.css( 'hh' , 'color' , 'red' );



//  引申拓展一下的话,如此就可以建一个自己写的 平常用的代码库


var Zxf = {
        Util: {
            method1: function(){
                console.log( "util mothod1")
            },
            method2: function () {

            }
        },
        Tools: {
            method1: function(){
                console.log( "tool mothod1")
            },
            method2: function () {

            }
        },
        Ajax: {
            method1: function(){
                console.log( "Ajax mothod1")
            },
            method2: function () {

            }
        }
    };
    Zxf.Util.method1();
    Zxf.Ajax.method1();



//  其他语言都有 自定义的 static 变量,不可修改, js也可以自己模仿这种操作
//  无法修改的static 静态变量
    var Conf = (function () {
        // 私有变量
        var conf = {
            MAX_NUM : 100,
            MIN_NUM : 1,
            COUNT : 1000
        };
        // 返回取值对象
        return{
            // 取值器方法
            get : function ( name ) {
                return conf[name] ? conf[name] : null;
            }
        }
    })();
    var count = Conf.get('COUNT');
    console.log( count );


 // 惰性单例, 也就是 用的时候才创建

var LazySingle = ( function () {
        // 单例实例引用
        var _instance = null;
        // 单例
        function Single(){
            //  定义私有属性和方法
            return {
                publicMethod: function () {

                },
                publicProperty: '1.1.1'
            }
        }
        // 获取单例对象接口
        return function () {
            // 如果为创建单例 将创建单例
            if( !_instance ){
                _instance = Single();
            }
            // 返回单力
            return _instance;
        }

    })();
    console.log( LazySingle().publicProperty );




猜你喜欢

转载自blog.csdn.net/zxf13598202302/article/details/79467815