js设计模式——代理模式

37 阅读1分钟

代理模式是为对象创建一个代用品或者占位符,以控制对一个对象的访问

应用:请求接口时做缓存代理

image.png

缓存代理的代码

 // 1.创建一个代用品来缓存对象
    const cache = {};
    //2.请求时进行判断,如果代理中有这个内容就不进行请求,如果没有就请求,并且将结果缓存到代理中
    async function getData(name) {
      if (!cache[name]) {
        const res = await axios({
          url: "lcoalhost:3000/list",
          params: {
            name,
          },
        });
        cache[name] = res.data;
      }
      //返回请求内容
      return cache[name];
    }