For training purpose I am already implemented samples of various variants of proxy design pattern implementation in ABAP and Java. And now I need to find a meaningful example for proxy pattern used in JavaScript.
Let’s review the concept of proxy pattern in Wikipedia:
“A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes. Use of the proxy can simply be forwarding to the real object, or can provide additional logic. In the proxy extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked. For the client, usage of a proxy object is similar to using the real object, because both implement the same interface.“
Let’s use a real case to illustrate its usage.
Normal Solution
I have an XML view which contains one Image control:And implement it in my controller.Nothing special. The drawback of this solution is, when you try to load a big image file, only a fragment of image is displayed first and then accompanied with the left part gradually.
Proxy Solution
New source code of controller:In this solution, once button is pressed:
(1) a local animation gif will be displayed as loading indicator.
(2) At the same time, a proxy Image instance is created which issues the load of the big file in secret.
(3) When the loading of big file is finished, the onload callback is called, and only at this time the image control defined in xml view itself could display the completely loaded image file.