A place holder object representing the true object. 由于一个对象不能够直接引用另一个对象,所以需要使用代理模式起到两个对象的中介作用。给其它对象提供一种代理以控制对这个对象的访问。
- 在JS中可以理解为:绑定上下文到对应函数上,参考:
$.proxy()
动机
需要占位符,比如确实需要这个对象的时候,才对它进行创建和初始化。比如图像的占位符。
适用性
- 「远程代理」:为一个对象在不同地址空间提供局部代表。
- 「虚代理」:根据需要来创建开销很大的对象。
- 「保护代理」:控制对原始对象的访问。
- 「智能指引」:取代了简单的指针,它在访问对象时执行一些附加的操作。
代码结构
Virtual Proxy
class ImageGraphic {draw() {}}class ImageProxy {public isInView() {}public draw() {if (this.isInView()) {return new ImageGraphic().draw();}return '';}}class Canvas {public images: ImageProxy[];draw() {this.images.forEach(image => image.draw());}}
Protection Proxy
class BankAccount {private _account;getAccount() {return this._account;}}class BankAccountProxy {private _bankAccount: BankAccount;isAuthorized() {};forbiddenOperation() {};getAccount() {if (this.isAuthorized()) {this._bankAccount.getAccount();} else {this.forbiddenOperation();}}}
实战
- Sandbox JS 沙箱中大量使用 proxy 去代理 window / document 等 BOM / DOM 对象,控制其访问,管理其声明周期;
