Proxy
Posted by Dustin Boston in Design Patterns.
The Proxy Pattern is a structural design pattern that provides a surrogate or placeholder for another object, controlling access and adding functionality without modifying the original object.
The Proxy Pattern is a structural design pattern that provides a surrogate or
placeholder for another object to control access to it. This pattern is useful
for adding functionality such as lazy initialization, access control, or logging
without altering the original object.
Source Code Listing
code.ts
type Subject = {
request(): void;
};
class RealSubject implements Subject {
request(): void {
console.log("Real subject");
}
}
class Proxy implements Subject {
private realSubject: RealSubject | undefined = undefined; // Lazy initialization
request(): void {
if (this.realSubject === undefined) {
// Check against null explicitly
this.realSubject = new RealSubject();
}
this.realSubject.request();
}
}
const client = {
run(): void {
const proxy: Subject = new Proxy(); // Type the proxy as Subject
proxy.request();
const proxy2 = new Proxy();
proxy2.request(); // The RealSubject is only created once
},
};
client.run();