< center>javascript proxy mode </center >

Posted by Oxymen on Tue, 30 Jul 2019 16:37:38 +0200

The so-called proxy pattern is to find a substitute object for an object in order to access the original object.

The reason why we use proxy is that we don't want or want to operate directly on the original object. We use proxy is to let it do a series of operations for the original object. After these things are done, we can tell the original object. Like the assistant brokers of the stars in our lives.

Let's give an example of a star buying shoes.
** 1. Stars buy shoes themselves.

// Define a shoe class
var Shoes = function(name){
    this.name = name;
};

Shoes.prototype.getName = function() {
    return this.name;
};

// Define a Star Object
var star = {
    buyShoes: function(shoes) {
        console.log('I got a pair.' + shoes.getName());
    }
}

star.buyShoes(new Shoes('leather shoes')); // "Buy a pair of leather shoes"

Of course, if you want to buy shoes, you usually leave it to your assistant.

2. Stars let assistants buy shoes for themselves.

// Define a shoe class
var Shoes = function(name){
    this.name = name;
};

Shoes.prototype.getName = function() {
    return this.name;
};

// Define an assistant object
 
var assistant = {
    buyShoes: function(shoes) {
        star.buyShoes(shoes.getName())
    }
};

// Define a Star Object
var star = {
    buyShoes: function(name) {
        console.log('I got a pair.' + name);
    }

};

assistant.buyShoes(new Shoes('High-heeled shoes')); // "Buy a pair of high heels"

Well, the agent is so simple. Some students may be confused here. Isn't the result of the agent implementation the same as that of not using it? Yes, the same result is necessary, but the value agent is not as complicated as we can see. The use scenario of the agent is not such a simple scenario, but for some more complex or special cases. Here is just to illustrate the implementation of the agent. Here are some usage scenarios.
Proxy usage scenarios
Continue the problem of the stars above buying shoes. In life, we will encounter stores in business hours, and you will find an agent during working hours, because you have to earn money and spend money at the same time; just like the Spring Festival is coming, you will find ticket vendors if you have no time or can't get tickets; like the present agent purchase, you can't go abroad, or you don't know about foreign countries. Just find someone who can go abroad and know something about foreign countries to help you buy things. We know that every store has its own business hours and breaks. Here we use (8:00-20:00) as business hours.

// Define a shoe class
var Shoes = function(name){
    this.name = name;
};

Shoes.prototype.getName = function() {
    return this.name;
};
// A business method is added to determine whether shoes can be bought by the current time.
Shoes.prototype.business = function() {
    var curTime = new Date().getHours();
    return  curTime >= 8 && curTime <= 20 ? that.getName() : '"Non-business hours!"';
    
}

// Define an assistant object
var assistant = {
    buyShoes: function(shoes) {
        star.buyShoes(shoes.getName())
    }
};

// Define a Star Object
var star = {
    buyShoes: function(name) {
        console.log('I got a pair.' + name);
    }
};

assistant.buyShoes(new Shoes('High-heeled shoes')); // "Buy a pair of high heels"

Protection Agent
As the agent of a star, an assistant can not only help the star buy things, but also help the star filter things. For example, there are fans who want to send star flowers (not all kinds of flowers are collected), and some people who want to find star endorsement advertisements (not all kinds of advertisements are endorsed).

// Define an advertising class
var Ad = function(price){
    this.price = price;
};

Ad.prototype.getPrice = function() {
    return this.price;
};

// Define an assistant object
var assistant = {
    init: function(ad) {
        var money = ad.getPrice();
        if(money > 300) {
            this.receiveAd(money);
        } else {
            this.rejectAd();
        }
    },
    receiveAd: function(price) {
        star.receiveAd(price);
    },
    rejectAd: function() {
        star.rejectAd();
    }
};

// Define a Star Object
var star = {
    receiveAd: function(price) {
        console.log('Advertising fees' + price + 'Ten thousand yuan');
    },
    rejectAd: function() {
        console.log('Refuse small production!');
    }
};

assistant.init(new Ad(5)); // "Refuse small production! "
assistant.init(new Ad(500)); // "Advertising costs 5 million yuan"

Stars like this authorize assistants, such as what price advertisements are acceptable, what flowers are acceptable, and so on. In this way, handing over some business to assistants or brokers, while they are behind the scenes, undoubtedly reduces their unnecessary troubles, so that stars are in a state of protection. In real life, there are many examples, and it is also common in our programming language development. Especially in the area of network and process, I believe that students who have done nodjs development will meet more or less.
Virtual Agent
In development, we often put the instantiation operation of the new Ad('5') object into the function to execute, which will reduce the overhead of the unnecessary instantiation object and cause waste of resources. This usage makes it a virtual agent.
Here's a common virtual agent, image preloading.
Picture preloading is a common front-end technology. Because the picture is too big or the network is not good, we will not directly set src attribute to an img tag node, but use a loading picture as a placeholder, and then use an asynchronous way to load the picture at home, until the picture is loaded, we will fill it into img. In the node.

var preImage = (function() {
    var imgNode = document.createElement('img');
    document.body.appendChild(imgNode);
    var img = new Image; 
    img.onload = function() {
        imgNode.src = img.src;
    }; 
 
    return {
        setSrc: function(src) {
            imgNode.src = '../loading.gif';
            img.src = src;
        }
    }
})(); 
 
preImage.setSrc('https://cn.bing.com/az/hprichbg/rb/TadamiTrain_ZH-CN13495442975_1920x1080.jpg'); 

At this point, the pre-loading function of the picture has been implemented, but it often reflects whether a piece of code is better or not, depending on whether your code is easy to maintain, especially for the large amount of code. First, this code does not meet a single responsibility, we are responsible for the image preloading function, img element processing in a function body, especially the part of the code changes and unchanged parts are not separated; second, our network speed is very good in the future, we do not have to worry about because the network does not. If the display effect is good, the function of image preloading should be removed.
We can try to use proxy to implement it. The code is as follows:

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

var preImage = (function() {
    var img = new Image; 
    img.onload = function() {
        myImage.setSrc = img.src;
    }; 
 
    return {
        setSrc: function(src) {
            myImage.setSrc( '../loading.gif');
            img.src = src;
        }
    }
})(); 
 
preImage.setSrc('https://cn.bing.com/az/hprichbg/rb/TadamiTrain_ZH-CN13495442975_1920x1080.jpg'); 

So we separate the image preload from setting src for the img element node.
Consistency between proxy and proxy objects
Because the proxy can achieve the same effect as the actual processing of the proxy object, so when implementing the physical object, the original object has the same method as the proxy object, so as to ensure that the user operates the proxy object just as he operates the original object.
Cache proxy
The caching proxy is to add the proxy to the cache. Here is an example of summation.

var multAdd = function() {
    var res = 0;
    for (var i = 0, l = arguments.length; i < l; i++) {
        res = res + arguments[i]
    }

    return res;
};

var proxyAdd = (function() {
    var cache = {};
    return function() {
        var args = Array.prototype.join.call(arguments, ',');
        if(args in cache) {
            return cache[args];
        }
        return caches[args] = multAdd.apply(this, arguments);
    }
})();

proxyAdd(1, 2, 3); // 6
proxyAdd(1, 2, 3); // 6

Of course, we can achieve cache sum without proxy, but in order to achieve a single responsibility, we can let multAdd achieve sum, and cache is implemented in proxy.
Of course, there are other classified agents, such as intelligent agents and remote agents. But in JavaScript, we use virtual proxy and cache proxy most frequently.

Topics: network Spring Programming less