代理设计模式
在我之前的博客中,我探讨了各种处理对象创建机制的创建型设计模式。现在,是时候深入探讨结构型设计模式了,它关注如何组合对象和类以形成更大的结构,同时保持其灵活性和高效性。让我们从代理设计模式开始。
JavaScript 中的代理设计模式
代理设计模式是一种结构化设计模式,它提供一个对象来代表另一个对象。它充当控制对真实对象的访问的中介,在不更改原始对象代码的情况下添加其他行为,例如延迟初始化、日志记录、访问控制或缓存。
在JavaScript 中,代理是 Proxy 对象提供的内置功能,允许您为基本操作(如属性访问、赋值、函数调用等)定义自定义行为。
我们什么时候需要代理模式?
代理模式在以下情况下特别有用:
- 延迟初始化:您想延迟创建资源密集型对象,直到需要它为止。
- 访问控制:您需要控制对对象的访问,例如,限制未经授权的访问或根据条件限制操作。
- 日志记录:您想要记录对象上的操作(例如,属性访问或方法调用)。
- 缓存:您希望缓存昂贵操作的结果以避免冗余计算。
代理模式的组件
- 主体:定义真实对象和代理的共同操作的接口。
- RealSubject:执行实际工作的实际对象。
- 代理:控制对 RealSubject 的访问的中介。
类比:
想象一下,你有一幅很大的画想给客人看,但要花很长时间才能从储藏室里拿出来(因为它很重,搬起来很费时间)。与其每次都等着,不如用一张印有这幅画的小明信片,在客人等待取画的时候快速展示给他们看。
在这个类比中:
- 大型绘画是真实的物体(就像需要时间加载的图像)。
- 明信片是代理(一种轻量级的替代品,在真实物体准备好之前一直存在)。
- 一旦真正的画作准备好了,您就可以将实物展示给您的客人。
现实世界的类比:
把房地产经纪人想象成一个代理。当您想要买房时,您不会立即参观每一栋房子(加载实际对象)。相反,房地产经纪人(代理)会先向您展示照片和描述。只有当您准备好购买时(即调用 display() 时),代理才会安排看房(加载实际对象)。
真实示例:图像加载(虚拟代理)
让我们以 Web 应用程序中的图片加载为例,我们希望延迟图片的加载,直到用户请求它(延迟加载)。代理可以充当占位符,直到真正的图片加载完成。
以下是如何在 JavaScript 中实现代理设计模式。
示例:图像加载代理
// Step 1: The real object
class RealImage {
constructor(filename) {
this.filename = filename;
this.loadImageFromDisk();
}
loadImageFromDisk() {
console.log(`Loading ${this.filename} from disk...`);
}
display() {
console.log(`Displaying ${this.filename}`);
}
}
// Step 2: The proxy object
class ProxyImage {
constructor(filename) {
this.realImage = null; // no real image yet
this.filename = filename;
}
display() {
if (this.realImage === null) {
// load the real image only when needed
this.realImage = new RealImage(this.filename);
}
this.realImage.display(); // display the real image
}
}
// Step 3: Using the proxy to display the image
const image = new ProxyImage("photo.jpg");
image.display(); // Loads and displays the image
image.display(); // Just displays the image (already loaded)
解释:
1). 真实图像:
- 该类
RealImage
代表实际图像。 - 它以文件名作为输入,并模拟从磁盘加载图像的耗时过程(由
loadImageFromDisk
方法显示)。 - 一旦加载,该
display
方法就用于显示图像。
2). 代理图像:
- 该类
ProxyImage
充当了 的替代品RealImage
。它不会立即加载真实图像。 - 它保存了对真实图像的引用(但最初是
null
因为真实图像尚未加载)。 - 当你在代理上调用该
display
方法时,它会检查真实图像是否已加载。如果没有,则先加载,然后再显示。
3).使用方法:
- 当我们创建 的实例时
ProxyImage
,实际图像尚未加载(因为它占用大量资源)。 - 第一次
display
调用时,代理加载图像(使用RealImage
类)然后显示它。 - 第二次
display
调用时,真实图像已经加载完毕,因此只显示图像,不再加载。
内置代理对象
ES6 代理由一个代理构造函数组成,该构造函数接受目标和处理程序作为参数
const proxy = new Proxy(target, handler)
这里,target
表示应用代理的对象,而handler是一个定义代理行为的特殊对象。
处理程序对象包含一系列具有预定义名称的可选方法,称为陷阱方法(例如apply,get,set和has),当在代理实例上执行相应操作时会自动调用这些方法。
让我们通过使用内置代理实现计算器来理解这一点
// Step 1: Define the Calculator class with prototype methods
class Calculator {
constructor() {
this.result = 0;
}
// Prototype method to add numbers
add(a, b) {
this.result = a + b;
return this.result;
}
// Prototype method to subtract numbers
subtract(a, b) {
this.result = a - b;
return this.result;
}
// Prototype method to multiply numbers
multiply(a, b) {
this.result = a * b;
return this.result;
}
// Prototype method to divide numbers
divide(a, b) {
if (b === 0) throw new Error("Division by zero is not allowed.");
this.result = a / b;
return this.result;
}
}
// Step 2: Create a proxy handler to intercept operations
const handler = {
// Intercept 'get' operations to ensure access to prototype methods
get(target, prop, receiver) {
if (prop in target) {
console.log(`Accessing property: ${prop}`);
return Reflect.get(target, prop, receiver); // Access property safely
} else {
throw new Error(`Property "${prop}" does not exist.`);
}
},
// Intercept 'set' operations to prevent mutation
set(target, prop, value) {
throw new Error(`Cannot modify property "${prop}". The calculator is immutable.`);
}
};
// Step 3: Create a proxy instance that inherits the Calculator prototype
const calculator = new Calculator(); // Original calculator object
const proxiedCalculator = new Proxy(calculator, handler); // Proxy wrapping the calculator
// Step 4: Use the proxy instance
try {
console.log(proxiedCalculator.add(5, 3)); // Output: 8
console.log(proxiedCalculator.multiply(4, 2)); // Output: 8
console.log(proxiedCalculator.divide(10, 2)); // Output: 5
// Attempt to access prototype directly through proxy
console.log(proxiedCalculator.__proto__ === Calculator.prototype); // Output: true
// Attempt to modify a property (should throw an error)
proxiedCalculator.result = 100; // Error: Cannot modify property "result".
} catch (error) {
console.error(error.message); // Output: Cannot modify property "result". The calculator is immutable.
}
使用代理的最好部分是这样的:
- 代理对象继承了原始计算器类的原型。
- 通过代理设置的陷阱可以避免变异。
守则解释
1).原型继承:
- 代理不会干扰计算器类的原始原型。
- 通过检查proxiedCalculator.proto === Calculator.prototype来确认。结果为true。
2).搬运get
操作:
- get 陷阱拦截代理对象上的属性访问。
- 我们使用它
Reflect.get
来安全地访问原始对象的属性和方法。
3).预防突变:
set
每当尝试修改目标对象的任何属性时,陷阱都会抛出错误。这确保了不变性。
4).通过代理使用原型方法:
代理允许访问诸如、、和等方法add
,所有subtract
这些方法都是在原始对象的原型上定义的。multiply
divide
这里要注意的关键点是:
- 保留原型继承:代理保留对所有原型方法的访问权限,使其行为与原始计算器相同。
- 防止变异:设置陷阱确保计算器对象的内部状态不会被意外改变。
- 安全访问属性和方法: get 陷阱确保仅访问有效属性,从而提高稳健性。
如果你已经读到这里,别忘了点赞❤️,并在下方留言,提出你的问题或想法。你的反馈对我来说至关重要,我期待听到你的反馈!
鏂囩珷鏉ユ簮锛�https://dev.to/srishtikprasad/proxy-design-pattern-4mm