The Proxy pattern puts a stand-in in front of the real object. The caller interacts with the proxy, which can add access control, logging, caching, or lazy loading before (and after) delegating to the actual implementation.
class RealSubject {
request() {
console.log("RealSubject: Handling request.");
}
}
class Proxy {
constructor(realSubject) {
this.realSubject = realSubject;
}
request() {
if (this.checkAccess()) {
this.realSubject.request();
this.logAccess();
}
}
checkAccess() {
console.log("Proxy: Checking access prior to firing a real request.");
// Simulate access check
return true;
}
logAccess() {
console.log("Proxy: Logging the time of request.");
}
}-
RealSubjectClass:- This class represents the real object that performs the actual work. It has a
requestmethod that logs a message indicating it is handling the request.
- This class represents the real object that performs the actual work. It has a
-
Proxy Class:
- This class acts as a proxy to the
RealSubject. It holds a reference to an instance ofRealSubjectand controls access to it. - The
requestmethod in theProxyclass first checks access by callingcheckAccess. If access is granted, it forwards the request to theRealSubjectand then logs the access by callinglogAccess.
- This class acts as a proxy to the
const realSubject = new RealSubject();
const proxy = new Proxy(realSubject);
proxy.request();- An instance of
RealSubjectis created. - An instance of
Proxyis created, with theRealSubjectinstance passed to its constructor. - The
requestmethod is called on theProxyinstance. This triggers the access check, forwards the request to theRealSubjectif access is granted, and logs the access.
RealSubject doesn't know it's being proxied; it just handles requests. All the cross-cutting concerns (access checks, logging) live in the proxy. This keeps each class focused on one job, and you can add or change proxy behavior without ever touching the underlying implementation.