In object-oriented design, there is a single responsibility principle, which means that in terms of a class (object, function), there should be only one reason for its change. If an object assumes too many responsibilities, it means it will become huge, and there are many reasons for its change. It couples these responsibilities together, which will make it difficult to maintain and refactor the program.
At this time, we can separate part of the responsibilities of the object (ontology) and give it to some third-party objects. The ontology only cares about some of its own core responsibilities, and these third-party objects are called agents. A proxy object can serve as the protector of an object (also called a "real subject"), allowing the real subject object to do as little work as possible. In the proxy design pattern, one object acts as the interface of another object.
Usually, the interface between the proxy and the ontology should be consistent, so that when no proxy is needed, the user can directly access the ontology.
When it is not convenient for us to directly access an object, we can consider recruiting an agent for the object.
Proxy can be used for: image preloading, merging HTTP requests (proxy collects all HTTP requests for a certain period of time and then sends them to the server at one time), lazy loading (processing and collecting some basic operations through proxy, and then loading the ontology only when the ontology is really needed), cache proxy (caches request results, calculation results), etc.
Example 1: Image preloading
var myImage = (function(){ var imgNode = document.createElement('img'); document.body.appendChild(imgNode); return { setSrc:function(src){ imgNode.src = src; } }})();//Proxy function var proxyImage = (function(){ var img = new Image; img.onload = function(){ myImage.setSrc(this.src); } return{ setSrc:function(src){ myImage.setSrc('loading.gif'); img.src = src; } }})();proxyImage.setSrc('show.jpg');The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.