First, the proxy mode definition
The key to proxy mode is to provide a surrogate object to control access to an object when the client is not convenient to access it directly or when it does not meet the needs. The proxy mode needs to provide the same interface as the ontology, which is transparent to the user . There are many types of proxy patterns, such as firewall proxies, protection agents (which help filter out requests, control the access of objects with different permissions), virtual proxies (to delay the creation of some expensive objects until they are really needed), cache proxies, and so on. The more virtual proxies are used in JavaScript.
Second, Virtual Agent Implementation Picture Preloading
In this case, the non-use of virtual agents is also able to solve the problem, but the use of virtual agents to better reflect the principle of single responsibility;
//proxy mode for picture preload varMyimage=(function () {varRealimg=document.createelement ('img'); Document.body.appendChild (REALIMG); return{setsrc:function (src) {realimg.src=src; } }; })(); varproxyimg=(function () {varimg=NewImage; Img.onload=function () {//myimage.setsrc (IMG.SRC);MYIMAGE.SETSRC ( This. SRC); } return{sersrc:function (src) {myimage.setsrc ("File://c:/users/Desktop/loading.gif"); IMG.SRC=src; } }; })(); //Invocation ModePROXYIMG.SETSRC ('http://imgcache.qq.com/00.jpg');
Third, Cache proxy
Caching proxies can provide temporary storage for some expensive computations, or, as Ajax paging, the same page of data theoretically only needs to be pulled back in the background, the data that has been pulled is cached somewhere, and the next time you request the same page, you can use the previous data directly.
//implementing caching proxies for complex operations /** * * * Calculation product * * **/function mult () {varret=1; for(varI=0; i<arguments.length;i++) {ret*=Arguments[i]; } returnret; } /** * * Create a factory ****** cache proxy*/ varcreateproxyfactory=function (FN) {varCache={}; returnfunction () {varArgstr=[].join.call (arguments); if(Argstrinchcache) { returnCACHE[ARGSTR]; } returnCache[argstr]=fn.call ( This, arguments); }; }; //Invoke Example varMult2=createproxyfactory (mult); MULT2 (1,2,3);//First time CalculationMULT2 (1,2,3);//second read from cache
JavaScript design Pattern Learning VI--proxy mode