代理设计模式

代理设计模式

在我之前的博客中,我探索了各种处理对象创建机制的创作设计模式。现在,是时候深入研究结构设计模式,它重点关注如何组合对象和类以形成更大的结构,同时保持它们的灵活性和高效性。让我们从代理设计模式开始

javascript 中的代理设计模式

代理设计模式是一种结构设计模式,它提供一个对象代表另一个对象。它充当控制对真实对象的访问的中介,添加附加行为,例如延迟初始化、日志记录、访问控制或缓存,而无需更改原始对象的代码。

javascript 中,代理是 proxy 对象提供的内置功能,允许您为属性访问、赋值、函数调用等基本操作定义自定义行为。

我们什么时候需要代理模式?

代理模式在以下情况下特别有用:

延迟初始化:您希望延迟创建资源密集型对象,直到需要它为止。访问控制:您需要控制对对象的访问,例如限制未经授权的访问或根据条件限制操作。日志记录:您想要记录对象上的操作(例如,属性访问或方法调用)。缓存:您想要缓存昂贵操作的结果以避免冗余计算。

代理模式的组成部分

主题: 定义真实对象和代理的公共操作的接口。realsubject: 执行实际工作的实际对象。代理: 控制对 realsubject 的访问的中介。

类比:

想象一下,您有一幅大画想要向客人展示,但需要花费很多时间才能从储藏室中取出它(因为它很重并且需要时间来搬运)。您决定使用这幅画的小明信片图像,在他们等待实际画作被获取时快速向他们展示,而不是每次都等待。

在这个比喻中:

大画是真实的物体(就像需要时间加载的图像)。明信片是代理(一种轻量级替代品,直到真实对象准备好为止)。一旦真正的画作准备好,您就可以向客人展示实际的画作。

现实世界的类比:

将房地产经纪人视为代理人。当你想买房子时,你不会立即参观每栋房子(加载实物)。相反,房地产经纪人(代理人)首先向您展示照片和描述。只有当你准备购买时(即,当你调用display()时),代理才会安排看房(加载实物)。

真实示例:图像加载(虚拟代理)

让我们使用 web 应用程序中的图像加载示例,我们希望延迟图像的加载,直到用户请求它(延迟加载)。代理可以充当占位符,直到加载真实图像。

以下是如何在 javascript 中实现代理设计模式。

示例:图像加载代理

// step 1: the real objectclass 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 objectclass 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 imageconst image = new proxyimage("photo.jpg");image.display(); // loads and displays the imageimage.display(); // just displays the image (already loaded)

说明:

1)。真实图像:

realimage类代表实际图像。它以文件名作为输入,并模拟从磁盘加载图像的耗时过程(由 loadimagefromdisk 方法显示)。加载后,将使用显示方法来显示图像。

2)。代理图像:

proxyimage类充当realimage的替代品。它不会立即加载真实图像。它包含对真实图像的引用(但最初它是空的,因为真实图像尚未加载)。当您在代理上调用显示方法时,它会检查真实图像是否已加载。如果没有,它会先加载,然后显示。

3)。用法:

当我们创建 proxyimage 实例时,实际图像尚未加载(因为它是资源密集型的)。第一次调用 display 时,代理加载图像(使用 realimage 类),然后显示它。第二次调用display时,真实图片已经加载完毕,所以只显示图片,不再加载。

内置proxy对象

es6 代理由一个代理构造函数组成,该构造函数接受目标和处理程序作为参数

代码小浣熊 代码小浣熊

代码小浣熊是基于商汤大语言模型的软件智能研发助手,覆盖软件需求分析、架构设计、代码编写、软件测试等环节

代码小浣熊 51 查看详情 代码小浣熊

const proxy = new proxy(target, handler)

这里,target代表应用代理的对象,而handler是一个特殊的对象,定义了代理的行为。

处理程序对象包含一系列具有预定义名称的可选方法,称为陷阱方法(例如 apply、get、set 和 has),当对代理实例执行相应操作时,这些方法会自动调用。

让我们通过使用内置代理实现计算器来理解这一点

// Step 1: Define the Calculator class with prototype methodsclass 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 operationsconst 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 prototypeconst calculator = new Calculator(); // Original calculator objectconst proxiedCalculator = new Proxy(calculator, handler); // Proxy wrapping the calculator// Step 4: Use the proxy instancetry {  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.}

使用代理的最佳部分是:代理对象继承了原calculator类的原型。通过代理设置的陷阱来避免突变。

代码说明

1)。 原型继承:

代理不会干扰 **calculator ** 类的原始原型。通过检查 proxiedcalculator.proto === calculator.prototype 来确认这一点。结果将是true

2)。 处理 getoperations:

get 陷阱拦截代理对象上的属性访问。我们使用 reflect.get 安全地访问原始对象的属性和方法。

3)。 防止突变:

每当尝试修改目标对象上的任何属性时,设置陷阱都会引发错误。这确保了不变性。

4)。 通过代理使用原型方法:

代理允许访问加、减、乘、除等方法,所有这些方法都在原始对象的原型上定义。

这里要观察的要点是:

保留原型继承:代理保留对所有原型方法的访问,使其行为类似于原始计算器。防止突变: 设置陷阱可确保计算器对象的内部状态不会被意外更改。安全访问属性和方法: get 陷阱确保仅访问有效的属性,从而提高鲁棒性。

如果您已经做到了这一步,请不要忘记点赞❤️,并在下面发表评论以提出任何问题或想法。您的反馈对我来说至关重要,我很乐意听到您的来信!

以上就是代理设计模式的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/437316.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月7日 16:52:20
下一篇 2025年11月7日 16:57:23

相关推荐

发表回复

登录后才能评论
关注微信