Proxy

Posted by Dustin Boston .


CAUTION

Construction Area
Watch out for:

  • Broken code
  • No comments
  • Partial examples
  • Missing tests

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();