Facade pattern of JS design pattern

concept

The Facade pattern provides a convenient high-level interface for larger code, which can hide the real complexity of its bottom layer.
Think of it as a simplified API to show to other developers.

Advantages and disadvantages

Advantage

  • Simplified interface
  • User and code decoupling
  • Easy to use

shortcoming

  • There are hidden costs and relatively poor performance

application

Chestnut 1

The $(el) in the jquery framework provides a simple external interface to realize the selection of various elements. Users do not need to manually call various methods inside the framework. It is easy to use. The following provides a simplified implementation of jq DOM selection.

jQuery = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context, rootjQuery );
};
        
jQuery.fn = jQuery.prototype = {
    init: function( selector, context, rootjQuery ) {
        var match, elem;

        // HANDLE: $(""), $(null), $(undefined), $(false)
        if ( !selector ) {
            return this;
        }

        // Handle HTML strings
        if ( typeof selector === "string" ) {
        
            ...

        } else if ( selector.nodeType ) {
           
            ...
           
        } else if ( jQuery.isFunction( selector ) ) {
           
           ...
           
        }

        return jQuery.makeArray( selector, this );
        //Convert an HTMLElements collection into a corresponding array pair, which can operate on the same class array as merge
    }
}

.css()

Chestnut 2

This example is a combination of facade pattern and module pattern, providing a simpler facade interface.

let module = (function() {
    var _private = {
        i: 5,
        get: function() {
            console.log('current value:' + this.i);
        },
        set: function(val) {
            this.i = val;
        },
        run: function() {
            console.log('running');
        },
        jump: function() {
            console.log('jumping');
        }
    },

    return {
        facade: function(args) {
            _private.set(args.val);
            _private.get();

            if(args.run) {
                _private.run();
            }
        }
    }
}());

module.facade({run: true, value: 10});

Reference resources

JavaScript Design Pattern

Tags: Javascript JQuery

Posted on Mon, 02 Dec 2019 10:30:09 -0800 by RossC0