Design Pattern Learning - (7. Singleton Pattern)

// Namespaces

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' );



// If you extend it, you can build a common code base written by yourself


var Zxf = {
        Useful: {
            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();



// Other languages ​​have custom static variables that cannot be modified, js can also imitate this operation by itself
// unmodifiable static static variable
    var Conf = (function () {
        // private variable
        var conf = {
            MAX_NUM : 100,
            MIN_NUM : 1,
            COUNT : 1000
        };
        // return the value object
        return{
            // getter method
            get : function ( name ) {
                return conf[name] ? conf[name] : null;
            }
        }
    })();
    var count = Conf.get('COUNT');
    console.log( count );


 // Lazy singleton, that is, it is only created when it is used

var LazySingle = (function () {
        // singleton instance reference
        var _instance = null;
        // singleton
        function Single(){
            // define private properties and methods
            return {
                publicMethod: function () {

                },
                publicProperty: '1.1.1'
            }
        }
        // Get the singleton object interface
        return function () {
            // If a singleton is created for a singleton, the singleton will be created
            if( !_instance ){
                _instance = Single();
            }
            // return single force
            return _instance;
        }

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




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326018505&siteId=291194637