Zachary W. Huang

Home Projects Blog Guides Resume

Proxy

Idea: Use a surrogate/placeholder to control access to a particular object. This enables behaviors such as: caching, lazy loading (copy-on-write), restricting permissions, and reference counting (smart pointers).

class Subject {
  request(_: string) {};
}

class RealSubject implements Subject {
  request(_: string) {
    console.log("Hello");
  }
}

class MyProxy implements Subject {
  realSubject: Subject;

  constructor(realSubject: Subject) {
    this.realSubject = realSubject;
  }

  request(pw: string) {
    // PLEASE DON'T EVER ACTUALLY DO THIS
    if (pw === "admin123") {
      this.realSubject.request(pw);
    }
  }
}

function main() {
  const subject = new RealSubject();
  const proxy = new MyProxy(subject);
  proxy.request("admin123"); // "Hello"
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024