代理模式

一、送花代理演示

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);
View Code

二、图片代理

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');
View Code

三、缓存代理

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));
  };
})();
View Code

 

posted @ 2019-06-19 16:45  shangyueyue  阅读(130)  评论(0编辑  收藏  举报