
在我之前的博客中,我探索了各种处理对象创建机制的创作设计模式。现在,是时候深入研究结构设计模式,它重点关注如何组合对象和类以形成更大的结构,同时保持它们的灵活性和高效性。让我们从代理设计模式开始
代理设计模式是一种结构设计模式,它提供一个对象代表另一个对象。它充当控制对真实对象的访问的中介,添加附加行为,例如延迟初始化、日志记录、访问控制或缓存,而无需更改原始对象的代码。
在 javascript 中,代理是 proxy 对象提供的内置功能,允许您为属性访问、赋值、函数调用等基本操作定义自定义行为。
代理模式在以下情况下特别有用:
想象一下,您有一幅大画想要向客人展示,但需要花费很多时间才能从储藏室中取出它(因为它很重并且需要时间来搬运)。您决定使用这幅画的小明信片图像,在他们等待实际画作被获取时快速向他们展示,而不是每次都等待。
在这个比喻中:
将房地产经纪人视为代理人。当你想买房子时,你不会立即参观每栋房子(加载实物)。相反,房地产经纪人(代理人)首先向您展示照片和描述。只有当你准备购买时(即,当你调用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)。真实图像:
2)。代理图像:
3)。用法:
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)。 原型继承:
2)。 处理 getoperations:
3)。 防止突变:
每当尝试修改目标对象上的任何属性时,设置陷阱都会引发错误。这确保了不变性。
4)。 通过代理使用原型方法:
代理允许访问加、减、乘、除等方法,所有这些方法都在原始对象的原型上定义。
这里要观察的要点是:
如果您已经做到了这一步,请不要忘记点赞❤️,并在下面发表评论以提出任何问题或想法。您的反馈对我来说至关重要,我很乐意听到您的来信!
以上就是代理设计模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号