」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 代理設計模式

代理設計模式

發佈於2024-11-06
瀏覽:874

Proxy Design Pattern

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

JavaScript 中的代理设计模式

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

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

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

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

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

代理模式的组成部分

  1. Subject: 定义真实对象和代理的通用操作的接口。
  2. RealSubject: 执行实际工作的实际对象。
  3. Proxy: 控制对 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 方法显示)。
  • 加载后,将使用显示方法来显示图像。

2)。代理图像:

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

3)。用法:

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

内置Proxy对象

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.
}

使用代理的最佳部分是:

  • 代理对象继承了原Calculator类的原型。
  • 通过代理设置的陷阱来避免突变。

代码说明

1)。 原型继承:

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

2)。 处理 getOperations:

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

3)。 防止突变:

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

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

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

这里要观察的要点是:

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

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

版本聲明 本文轉載於:https://dev.to/srishtikprasad/proxy-design-pattern-4mm?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3