The Proxy pattern is used to control access to an object by placing a surrogate or placeholder object (the proxy) in front of the real object (the real subject).
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.
The Proxy pattern is used to control access to an object. In this example, the Proxy class controls access to the RealSubject by checking access and logging the request. This pattern is useful for adding additional functionality (like access control and logging) without modifying the original class.