Proxy Pattern

Provide a proxy for other objects to control access to that object.

There are several variations of the proxy pattern in common use:

  • Protection agency
  • Virtual agent
  • The caching proxy

1. Protect the agent

The protection proxy is used to control the access of objects with different permissions to the target object

  • For example,
class Car {
    drive() {
        return "driving";
    };
}

class CarProxy {
    constructor(driver) {
        this.driver = driver;
    }
    drive() {
        // Protection agent, only 18 years old can drive
        return (this.driver.age < 18)?"too young to drive" : new Car().drive();
    };
}
Copy the code

2. Virtual proxy

Virtual proxies can be used for lazy loading of images, lazy loading, merging HTTP requests, etc

  • Example: lazy loading of images
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Lazy loading of images</title>
    <style>
        img {
            display: block;
            width: 400px;
            height: 300px;
            margin-bottom: 200px;
        }
    </style>
</head>
<body>
    <img data-src="./images/1.jpg" alt="">
    <img data-src="./images/2.jpg" alt="">
    <img data-src="./images/3.jpg" alt="">
    <img data-src="./images/4.jpg" alt="">
</body>
<script>
    var imgs = document.querySelectorAll('img');
    //offsetTop is the distance between the element and offsetParent, looped to the top of the page
    function getTop(e) {
    var T = e.offsetTop;
        while(e = e.offsetParent) {
            T += e.offsetTop;
        }
        return T;
    }
    function lazyLoad(imgs) {
        var H = document.documentElement.clientHeight;// Get the height of the visible area
        var S = document.documentElement.scrollTop || document.body.scrollTop;
        for (var i = 0; i < imgs.length; i++) {
            if (H + S > getTop(imgs[i])) {
                imgs[i].src = imgs[i].getAttribute('data-src'); }}}window.onload = window.onscroll = function () { //onscroll() is triggered when the scroll bar is scrolling
        lazyLoad(imgs);
    }
</script>
</html>
Copy the code

3. Cache proxy

Caching proxies can be used to: cache Ajax asynchronous request data, compute products, and so on

  • Example: Caching Ajax request data
const getData = (function() {
    const cache = {};
    return function(url) {
        if (cache[url]) {
            return Promise.resolve(cache[url]);
        }
        return $.ajax.get(url).then((res) = > {
            cache[url] = res;
            return res;
        }).catch(err= > console.error(err))
    }
})();

getData('/getData'); // Initiate an HTTP request
getData('/getData'); // Return cached data
Copy the code

conclusion

The proxy pattern includes many subcategories, the most commonly used in JavaScript development being virtual proxies and caching proxies. While the proxy pattern is very useful, it is often not necessary to anticipate the need to use the proxy pattern when writing business code. It’s never too late to write a proxy when you really find it inconvenient to access an object directly.