A place holder object representing the true object. 由于一个对象不能够直接引用另一个对象,所以需要使用代理模式起到两个对象的中介作用。给其它对象提供一种代理以控制对这个对象的访问。

  • 在JS中可以理解为:绑定上下文到对应函数上,参考:$.proxy()

动机

需要占位符,比如确实需要这个对象的时候,才对它进行创建和初始化。比如图像的占位符。

适用性

  • 「远程代理」:为一个对象在不同地址空间提供局部代表。
  • 「虚代理」:根据需要来创建开销很大的对象。
  • 「保护代理」:控制对原始对象的访问。
  • 「智能指引」:取代了简单的指针,它在访问对象时执行一些附加的操作。

代码结构

Virtual Proxy

  1. class ImageGraphic {
  2. draw() {}
  3. }
  4. class ImageProxy {
  5. public isInView() {}
  6. public draw() {
  7. if (this.isInView()) {
  8. return new ImageGraphic().draw();
  9. }
  10. return '';
  11. }
  12. }
  13. class Canvas {
  14. public images: ImageProxy[];
  15. draw() {
  16. this.images.forEach(image => image.draw());
  17. }
  18. }

Protection Proxy

  1. class BankAccount {
  2. private _account;
  3. getAccount() {
  4. return this._account;
  5. }
  6. }
  7. class BankAccountProxy {
  8. private _bankAccount: BankAccount;
  9. isAuthorized() {};
  10. forbiddenOperation() {};
  11. getAccount() {
  12. if (this.isAuthorized()) {
  13. this._bankAccount.getAccount();
  14. } else {
  15. this.forbiddenOperation();
  16. }
  17. }
  18. }

实战

  • Sandbox JS 沙箱中大量使用 proxy 去代理 window / document 等 BOM / DOM 对象,控制其访问,管理其声明周期;