代理模式
一、送花代理演示
class Flower { constructor(price) { this.price = price; } } const boy = { name: 'jack', flower: new Flower(120), send(person) { person.receive(this.flower); }, }; const proxyer = { name: 'proxyer', receive(flower) { if (flower.price > 100) { girl.receive(flower); } }, }; const girl = { name: 'alice', receive(flower) { console.log(this.name, flower.price); }, }; boy.send(proxyer);
二、图片代理
let imageNode = (function(){ let imgNode = document.appendChild(document.createElement('img')) return{ setSrc(src){ imgNode.src=src; } } })(); let proxy = (function(){ let img = new image(); img.onload(){ imageNode.setSrc(img.src); } return { setSrc(src){ imageNode.setSrc('loading.png'); img.src = src; } } }(); proxy.setSrc('001.png');
三、缓存代理
const mult = (...args) => { return args.reduce((pre, cur) => pre * cur); }; const proxy = (function() { const cache = {}; return (...args) => { const key = args.join(','); return cache[key] || (cache[key] = mult(...args)); }; })();