代理模式

为一个对象提供一个代用品或占位符,以便控制对它的访问

  • 虚拟代理
//真正的图片
let myImage = (function () {
    let imgNode = document.createElement('img');
    document.body.appendChild(imgNode);
    return {
        setSrc: function (src) {
            imgNode.src = src;
        }
    }
})();
//图片代理
let proxyImage = (function () {
    let img = new Image;
    img.onload = function () {
        myImage.setSrc(this.src);
    }
    return {
        setSrc: function (src) {
            myImage.setSrc('./loading.svg');
            img.src = src;
        }
    }
})();
proxyImage.setSrc('http://www.cdhrsip.com/static/imgs/high-tech/banner.png?version=201512141756');
  • 缓存代理
let mult = function () {
    console.log('开始计算乘积');
    let a = 1;
    for (let i = 0, l = arguments.length; i < l; i++) {
        a = a * arguments[i];
    }
    return a;
};
let proxyMult = (function () {
    let cache = {};
    return function () {
        let args = Array.prototype.join.call(arguments, ',');
        if (args in cache) {
            return cache[args];
        }
        return cache[args] = mult.apply(this, arguments);
    }
})();
console.log(proxyMult(1, 2, 3, 4)); // 输出:24
console.log(proxyMult(1, 2, 3, 4)); // 输出:24
Copyright © lujiannb@qq.com 2021 all right reserved,powered by Gitbook该文章修订时间: 2024-06-06 11:32:07

results matching ""

    No results matching ""