Here is a concise front-end knowledge system waiting for you to check, have a look, there will be a surprise oh, if you feel good, begged star ha ~


Brief introduction to the proxy pattern

A proxy is an object that has the same interface as an ontology object to achieve access control over the ontology object.

In short, ontology objects focus only on the implementation of business logic, while proxies control the instantiation (when instantiated and when used) of ontology objects.

The advantage of the proxy mode is that the proxy object can be instantiated instead of the ontology object, but the ontology object is not instantiated until the appropriate time.

The proxy pattern can delay the creation of expensive ontology objects, delaying instantiation of the ontology until methods are called.

A simple example

// Declare the girl object var girl =function(name) { this.name = name; }; // Declare the boy object var boy =function (girl) {
    this.girl = girl;
    this.sendGift = function (gift) {
        alert("Hi " + girl.name + ", the boy gives you a gift:"+ gift); }}; // Declare proxy object var proxyObj =function (girl) {
    this.girl = girl;
    this.sendGift = function(gift) { (new boy(girl)).sendGift(gift); // Send flowers to Dudu}}; var proxy = new proxyObj(new girl("Flower"));
proxy.sendGift("999 Roses");
Copy the code

As shown in the code above, girl is the object to be given a gift, boy is the object to be given a gift, he saves the attribute of girl, and there is also a method to send a gift, sendGift, and then he completes the task through proxyObj, proxyObj is the proxy, he sends the gift of boy to girl, Therefore, proxyObj also needs to save girl’s attributes, and also has sendGift method, which instantiates the ontology object boy and calls boy’s sendGift method to complete the process of boy sending a gift to girl.

Practice 1: Picture loading

In front-end development, it is very common to use images. If the SRC attribute is directly set to the IMG tag, if the image is too large or the network speed is slow, the image will be blank for a period of time in the loading process, resulting in poor user experience.

Traditional solutions

The traditional solution is to use a loading icon as a placeholder before an image is loaded. After an image is loaded, use a real image address to replace the loading icon. As follows:

Var myImage = ();function(){
    var imgNode = document.createElement("img");
    document.body.appendChild(imgNode);
    var img = new Image();
    img.onload = function(){
        imgNode.src = this.src;
    };
    return {
        setSrc: function(src) {
            imgNode.src = "http://img.lanrentuku.com/img/allimg/1212/5-121204193R0.gif";
            img.src = src;
        }
    }
})();
// 调用方式
myImage.setSrc("https://www.baidu.com/img/bd_logo1.png");
Copy the code

Myimage.setsrc = myimage.setsrc = myimage.setsrc = myimage.setsrc = myimage.setsrc = myimage.setsrc = myImage.setsrc = myImage.setsrc = myImage.setsrc = myImage.setsrc = myImage.setsrc = myImage.setsrc = myImage.setsrc = myImage.setsrc = myImage.setsrc = myImage.setsrc = myImage.setsrc

This scheme can realize functions, but it also has obvious defects: the coupling is too high, and the myImage function violates the single responsibility principle in object-oriented design principle, and simultaneously completes multiple tasks such as creating IMG and setting loading state.

At this point, the proxy mode can be used to implement ~~~

Proxy mode solution

var myImage = (function(){
    var imgNode = document.createElement("img");
    document.body.appendChild(imgNode);
    return {
        setSrc: function(src) { imgNode.src = src; }}}) (); Var ProxyImage = (function(){
    var img = new Image();
    img.onload = function(){
        myImage.setSrc(this.src);
    };
    return {
        setSrc: function(src) {
        myImage.setSrc("http://img.lanrentuku.com/img/allimg/1212/5-121204193R0.gif");
        img.src = src;
        }
    }
})();
// 调用方式
ProxyImage.setSrc("https://www.baidu.com/img/bd_logo1.png");
Copy the code

As shown in the above code, the myImage function is only responsible for one thing: create img elements and add them to the page. The loading loading image is entrusted to the proxy function ProxyImage. When the image is loaded successfully, the proxy function ProxyImage will inform and execute the method of myImage function. At the same time, when we do not need the proxy object in the future, we can directly call the ontology object method.

The proxy mode has the same external interface with the ontology object, which has two advantages: first, users can request the proxy without knowing the implementation process of the proxy, as long as the results meet the expectations. If the proxy object is no longer needed, this method can be used to call the ontology object instead. 2. Proxy substitution can be used wherever the ontology object is used.

Finally, it is important to note that the principal object and the proxy object can both return an anonymous function and thus be considered to have the same interface.

Practice 2: Caching proxy

Cache the results of the first run. When the same operation is run again, it is directly fetched from the cache to avoid repeated operations. If the operation is very complex, the performance is expensive, so using cache objects can improve performance. Here’s a simple example:

var mult = function(){
    var a = 1;
    for(var i = 0,ilen = arguments.length; i < ilen; i+=1) {
        a = a*arguments[i];
    }
    returna; }; // Calculate addition var plus =function(){
    var a = 0;
    for(var i = 0,ilen = arguments.length; i < ilen; i+=1) {
        a += arguments[i];
    }
    returna; } // proxy function var proxyFunc =function(fn) { var cache = {}; // Cache objectsreturn function(){
        var args = Array.prototype.join.call(arguments,', ');
        if(args in cache) {
            returncache[args]; // Use cache proxy}returncache[args] = fn.apply(this,arguments); }}; var proxyMult = proxyFunc(mult); The console. The log (proxyMult (1, 2, 3, 4)); / / 24 console. The log (proxyMult (1, 2, 3, 4)); Var proxyPlus = proxyFunc(plus); The console. The log (proxyPlus (1, 2, 3, 4)); / / 10. The console log (proxyPlus (1, 2, 3, 4)); // cache access 10Copy the code

The above code is the common addition and multiplication operations on the Internet. By caching the proxy, you can reduce unnecessary computation.