StructuralTypeScriptverifiedVerified

Proxy Pattern in TypeScript

Provides a surrogate or placeholder for another object to control access, add lazy initialization, caching, logging, or access control.

How to Implement the Proxy Pattern in TypeScript

1Step 1: Define the subject interface and real implementation

interface Subject {
  request(): void;
}

class RealSubject implements Subject {
  request(): void {
    console.log("RealSubject: handling request.");
  }
}

2Step 2: Create the proxy with access control and logging

class ProxySubject implements Subject {
  private realSubject: RealSubject;

  constructor(realSubject: RealSubject) {
    this.realSubject = realSubject;
  }

  private checkAccess(): boolean {
    console.log("Proxy: checking access before forwarding request.");
    return true; // simplified – could consult auth service
  }

  private logAccess(): void {
    console.log("Proxy: logging time of request.");
  }

  request(): void {
    if (this.checkAccess()) {
      this.realSubject.request();
      this.logAccess();
    }
  }
}

3Step 3: Access the real subject through the proxy

function clientCode(subject: Subject): void {
  subject.request();
}

const real = new RealSubject();
clientCode(real);

console.log("---");

const proxy = new ProxySubject(real);
clientCode(proxy);

Proxy Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Proxy Pattern in the Real World

A corporate receptionist acts as a proxy for the CEO. When someone wants to meet the CEO, the receptionist checks credentials, schedules the meeting, and logs the visit before granting access. The visitor interacts with the receptionist using the same protocol they would use with the CEO—the receptionist simply adds control and record-keeping around that access.