Proxy design Pattern {Structural)
The objects participating in this pattern are:
Client -- In sample code: the run() function
calls Proxy to request an operation
Proxy -- In sample code: 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
defines the real object for which service is requested
by bhupendra negi
November 26, 2015
HTML
<p> Proxy Design Pattern </p>
<input type ="button" value="SEE PROXY PATTERN" onclick="run()"/>
JavaScript
// this is client
// log helper
var log = (function() {
var log = "";
return {
add: function(msg) { log += msg + "\n"; },
show: function() { alert(log); log = ""; }
}
})();
function run() {
console.log("run again");
var geo = new GeoProxy();
// geolocation requests
geo.getLatLng("Paris");
geo.getLatLng("London");
geo.getLatLng("London");
geo.getLatLng("London");
geo.getLatLng("London");
geo.getLatLng("Amsterdam");
geo.getLatLng("Amsterdam");
geo.getLatLng("Amsterdam");
geo.getLatLng("Amsterdam");
geo.getLatLng("London");
geo.getLatLng("London");
log.add("\nCache size: " + geo.getCount());
log.show();
}
//this is subject
function GeoCoder() {
this.getLatLng = function(address) {
if (address === "Amsterdam") {
return "52.3700° N, 4.8900° E";
} else if (address === "London") {
return "51.5171° N, 0.1062° W";
} else if (address === "Paris") {
return "48.8742° N, 2.3470° E";
} else if (address === "Berlin") {
return "52.5233° N, 13.4127° E";
} else {
return "";
}
};
}
// this is proxy
function GeoProxy() {
var geocoder = new GeoCoder();
var geocache = {};
return {
getLatLng: function(address) {
if (!geocache[address]) {
geocache[address] = geocoder.getLatLng(address);
}
log.add(address + ": " + geocache[address]);
return geocache[address];
},
getCount: function() {
var count = 0;
for (var code in geocache) { count++; }
return count;
}
};
}