什么是 JavaScript“代理模式”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7379732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a JavaScript "Proxy Pattern"?
提问by Andrei Oniga
I've come across the notion of 'Proxy Pattern' today on jQuery.com, but could not make anything of it. Apparently it is of great use, but I do not understand the idea at all, it sounds alien to me. Could someone please explain it to me in simple terms, "as if I were a 3 year old"?
我今天在 jQuery.com 上遇到了“代理模式”的概念,但什么也做不了。显然它很有用,但我根本不明白这个想法,这对我来说听起来很陌生。有人可以简单地向我解释一下,“好像我是一个 3 岁的孩子”?
回答by Ivan
Imagine you have site with many ajax requests. There is a change in design. Now before each request you want to display some custom loading gif. You neeed to change all the code where there is an ajax request or you can use proxy pattern.
想象一下,您有一个包含许多 ajax 请求的站点。设计有变化。现在在每个请求之前你想要显示一些自定义加载 gif。您需要更改所有有 ajax 请求的代码,或者您可以使用代理模式。
var proxied = jQuery.ajax; // Preserving original function
jQuery.ajax = function() {
jQuery("#loading").dialog({modal: true});
return proxied.apply(this, arguments);
}
回答by Alex Figueiredo
In Javascript Patterns book, Stoyan Stefanov describes this pattern as so:
在 Javascript Patterns 一书中,Stoyan Stefanov 将这种模式描述为:
In the proxy pattern, one object acts as an interface to another object. The proxy sits between the client of an object and the object itself and protects the access to that object.
在代理模式中,一个对象充当另一个对象的接口。代理位于对象的客户端和对象本身之间,并保护对该对象的访问。
This pattern might look like an overhead but it's useful for perfomance purposes. The proxy servers play a guardian role for the object (also called "real subject") and tries to make this object do as little work as possible.
这种模式可能看起来像一个开销,但它对于性能目的很有用。代理服务器扮演对象(也称为“真实主体”)的守护者角色,并尝试使该对象尽可能少地工作。
A real world example
一个真实世界的例子
The proxy pattern is useful when the real subject does something expensive. In web applications, one of the most expensive operations you can do is a network request, so it makes sense to combine HTTP requests as much as possible.
当真实主体做了一些昂贵的事情时,代理模式很有用。在 Web 应用程序中,您可以执行的最昂贵的操作之一是网络请求,因此尽可能组合 HTTP 请求是有意义的。
You can see an example here: http://www.jspatterns.com/book/7/proxy.html. (take a look at the source code).
您可以在此处查看示例:http: //www.jspatterns.com/book/7/proxy.html。(看看源代码)。
You have a list of videos on the page. When the user clicks a video title, the area below the title expands to show more information about the video and also enables the video to be played. The detailed video information and the URL of the video are not part of the page; they need to be retrieved by making a web service call. The web service can accept multiple video IDs, so we can speed up the application by making fewer HTTP requests whenever possible and retrieving data for several videos at one time.
您在页面上有一个视频列表。当用户单击视频标题时,标题下方的区域会展开以显示有关视频的更多信息,并且还可以播放视频。详细的视频信息和视频的 URL 不属于页面的一部分;它们需要通过 Web 服务调用来检索。Web 服务可以接受多个视频 ID,因此我们可以通过尽可能减少 HTTP 请求并一次检索多个视频的数据来加速应用程序。
The videosobject doesn't call the HTTPservice directly but calls the proxyinstead. The proxy then waits before forwarding the request. If other calls from videos come in the 50ms waiting period, they will be merged into one. A delay of 50ms is pretty much imperceptible for the user but can help combine requests and speed up the experience when clicking “toggle” and expanding more than one video at once. It also reduces the server load significantly since the web server has to handle a smaller number of requests.
该视频对象不调用HTTP直接服务,但呼叫代理来代替。然后代理在转发请求之前等待。如果来自视频的其他呼叫在 50 毫秒的等待期内到来,它们将合并为一个。50 毫秒的延迟对于用户来说几乎是察觉不到的,但可以帮助合并请求并在单击“切换”并一次展开多个视频时加快体验。它还显着降低了服务器负载,因为 Web 服务器必须处理较少数量的请求。
Without proxy
无代理
Proxy
代理人
Proxy as a cache
代理作为缓存
回答by ZenMaster
In general - Proxy Pattern comes to control access to a resource. By doing so it can solve several potential issues:
一般来说 - 代理模式来控制对资源的访问。通过这样做,它可以解决几个潜在的问题:
- prevent incorrect or malicious use of the resource
- prevent/control access to a resource that is too expensive to create
- 防止不正确或恶意使用资源
- 防止/控制对创建成本太高的资源的访问
jQuery use the term rather loosely, but their idea is that you override/hide the existing method (in their example jQuery.fn.setArray
) while adding more functionality to it.
jQuery 相当松散地使用该术语,但他们的想法是覆盖/隐藏现有方法(在他们的示例中jQuery.fn.setArray
),同时向其添加更多功能。
(function() { // envelop everyting in anonymous immediately called function
var proxied = jQuery.fn.setArray; // save current method
jQuery.fn.setArray = function() { // override the method
console.log(this, arguments); // add functionality
return proxied.apply(this, arguments); // call original method and return
// its result
};
})();
回答by jfriend00
Here's one example of a proxy pattern used to record what listeners are being set: Why does Google +1 record my mouse movements?.
这是用于记录正在设置的侦听器的代理模式的一个示例:为什么 Google +1 会记录我的鼠标移动?.
回答by FraZer
The Proxy pattern provides a surrogate or placeholder object for another object and controls access to this other object.
代理模式为另一个对象提供代理或占位符对象,并控制对另一个对象的访问。
In object-oriented programming, objects do the work they advertise through their interface (properties and methods). Clients of these objects expect this work to be done quickly and efficiently. However, there are situations where an object is severely constrained and cannot live up to its responsibility. Typically this occurs when there is a dependency on a remote resource (resulting in network latency) or when an object takes a long time to load.
在面向对象的编程中,对象通过它们的接口(属性和方法)来完成它们所宣传的工作。这些对象的客户希望快速有效地完成这项工作。但是,也存在对象受到严重约束而无法履行其职责的情况。通常,当依赖远程资源(导致网络延迟)或对象需要很长时间才能加载时,就会发生这种情况。
In situations like these you apply the Proxy pattern and create a proxy object that ‘stands in' for the original object. The Proxy forwards the request to a target object. The interface of the Proxy object is the same as the original object and clients may not even be aware they are dealing with a proxy rather than the real object.
在这种情况下,您可以应用代理模式并创建一个“代表”原始对象的代理对象。代理将请求转发到目标对象。Proxy 对象的接口与原始对象相同,客户端甚至可能不知道他们正在处理代理而不是真实对象。
Client-- In sample code: the run() function
客户端——在示例代码中:run() 函数
- calls Proxy to request an operation.
- 调用 Proxy 请求操作。
Proxy-- In sample code: GeoProxy
代理——在示例代码中:GeoProxy
provides an interface similar to the real object
maintains a reference that lets the proxy access the real object
handles requests and forwards these to the real object
提供类似于实物的接口
维护一个引用,让代理访问真实对象
处理请求并将这些请求转发给真实对象
RealSubject-- In sample code: GeoCoder
RealSubject-- 在示例代码中:GeoCoder
- defines the real object for which service is requested
- 定义请求服务的真实对象