Writing in the front

Recently, I am studying the book JavaScript Design Pattern and Development Practice. Every time I finish reading a module, I will write a document as a note. If you are also learning JS design pattern, welcome to leave a message.

The principle of

Proxy mode, as the name implies, is to add a layer of proxy to the same thing. The key of proxy mode is to provide a proxy object to control the access to an object when it is inconvenient for the customer to directly access an object or does not meet the needs. The customer actually accesses the proxy object. After doing some processing on the request, the proxy object passes the request to the ontology object.

On the other hand, when an object has too much to do to violate the single function principle, consider creating its proxy object to split functionality.

One, protect the agent

Suppose xiao Ming to mm confession, through a friend, send a bunch of flowers, but the time to send a friend to confirm the MM mood, send the action also need a friend to complete, otherwise the flowers will be wasted, the friend here is a protection agent.

Let’s write Xiaoming’s object first

var Flower = function(){};
var xiaoming = {
 sendFlower: function( target){
 var flower = newFlower(); target.receiveFlower( flower ); }}; xiaoming.sendFlower( B );Copy the code

Then write the proxy object and the MM

Var proxy = {receiveFlower: function(flower){MM. ListenGoodMood (function(){var flower = new flower (); MM. ReceiveFlower (flower); }); }}; Var MM = {receiveFlower: function(flower){console.log(' receiveFlower '+ flower); }, // listenGoodMood: function(fn){setTimeout(function(){fn(); }, 10000); }};Copy the code

Finally, call xiaoming. SendFlower (proxy) to send flowers

Second, virtual proxy

Virtual proxy is generally used to set a layer of proxy for the target object, and then perform some operations through the proxy to save resources or facilitate use.

1. Image preloading

In Web development, image preloading is a common technique. If you directly set the SRC attribute to an IMG tag node, the position of the image will be blank for a period of time due to the large image or poor network. A common practice is to load the image asynchronously with a loading image, and then fill the image into the IMG node after the image is loaded. This scenario is suitable for using a virtual agent.

Let’s start by writing the code that creates the node

var myImage = (function(){
 var imgNode = document.createElement( 'img' );
 document.body.appendChild( imgNode );
 return {
 setSrc: function( src ){ imgNode.src = src; }}}) ();Copy the code

Then create a layer of proxies for it

var proxyImage = (function(){ var img = new Image; img.onload = function(){ myImage.setSrc( this.src ); } / / return a placeholder image return {setSrc: function (SRC) {myimage.png setSrc (' file:// / C: / Users/svenzeng/Desktop/loading. GIF "); img.src = src; }}}) (); proxyImage.setSrc( 'http:// imgcache.qq.com/music/photo/k/000GGDys0yA0Nk.jpg' );Copy the code

2. Merge HTTP requests

Assuming that every click on the DOM on the page requires an HTTP request to be sent, which can be very performance consuming, we can use proxies to collect HTTP requests over a period of time and send them uniformly.

Start by writing the component that sends the request


var checkbox = document.getElementsByTagName( 'input' );
    for ( var i = 0, c; c = checkbox[ i++ ]; ) { c.onclick =function(){
         if ( this.checked === true ){
             proxySynchronousFile( this.id ); }}};Copy the code

Write a unified sending agent

var synchronousFile = function( id ){
 console.log( 'Start file synchronization with id:' + id );
};
var proxySynchronousFile = (function(){
     var cache = [], // Save the ids to be synchronized over a period of time
     timer; / / timer
     return function( id ){
         cache.push( id );
         if ( timer ){ // Ensure that the started timer is not overwritten
             return;
         }
         timer = setTimeout(function(){
             synchronousFile( cache.join( ', '));// Send the set of ids to be synchronized to the ontology after 2 seconds
             clearTimeout( timer ); // Empty the timer
             timer = null;
             cache.length = 0; // Clear the ID collection
         }, 2000 );
     }
})();
Copy the code

3. Lazy loading

Let’s say we want to load a modal box on the page, but if the user doesn’t want to load it, it will cost some resources. So we will load the modal box when the user uses its functionality, but in order not to affect usage, we need to provide a proxy object for the user to use before loading the actual modal box. When the modal box is actually loaded, the user clicks the logic.

Third, cache proxy

The caching proxy can provide temporary storage for some expensive results, and then return the results directly on the next operation if the same number of parameters is passed in.

1. Compute the product

// Create a function to evaluate the product:
       var mul = function(x,y){
           return x*y;
       }
Copy the code

Now add the cache function

       var mulProxy = function(){
           var ache = [];
            return function(x,y){
                exitArr = ache.filter(item= > item.x == x && item.y == y);
            if(exitArr.length>0) {console.log('Get by cache');
                return exitArr[0].result;
            }else{
                console.log('By calculation');
                var result = mul(x,y);
                ache.push({
                    x,
                    y,
                    result
                });
                returnresult; }}}var mulProxyFunc = mulProxy();
Copy the code

2. High-order functions create dynamic proxies

/**************** computes the product *****************/
var mult = function(){
 var a = 1;
 for ( var i = 0, l = arguments.length; i < l; i++ ){
 a = a * arguments[i];
 }
 return a;
};
/**************** calculates plus and *****************/
var plus = function(){
 var a = 0;
 for ( var i = 0, l = arguments.length; i < l; i++ ){
 a = a + arguments[i];
 }
 return a;
};
/**************** Create a factory for caching proxies *****************/
var createProxyFactory = function( fn ){
 var cache = {};
 return function(){
 var args = Array.prototype.join.call( arguments.', ' );
 if ( args in cache ){
 return cache[ args ];
 }
 return cache[ args ] = fn.apply( this.arguments); }};var proxyMult = createProxyFactory( mult ),
proxyPlus = createProxyFactory( plus );
alert ( proxyMult( 1.2.3.4));// Output: 24
alert ( proxyMult( 1.2.3.4));// Output: 24
Copy the code

The last

This article introduces three cases of proxy patterns in JS design patterns. If you find this article useful, you may wish to give it a thumbs up.