← Back to Home

Proxy Pattern

Provide a surrogate or placeholder for another object to control access to it. Useful for lazy loading, access control, logging, etc.

What is it?

The Proxy pattern controls access to another object by serving as a stand-in. It can delay instantiation, reduce load time, or add additional behavior.

Example

interface Image {
  display(): string;
}

class RealImage implements Image {
  constructor(private filename: string) {
    console.log(`Loading ${filename} from disk...`);
  }

  display() {
    return `🖼️ Displaying ${this.filename}`;
  }
}

class ProxyImage implements Image {
  private realImage: RealImage | null = null;

  constructor(private filename: string) {}

  display() {
    if (!this.realImage) {
      this.realImage = new RealImage(this.filename);
    }
    return this.realImage.display();
  }
}

const proxy = new ProxyImage('design-patterns.png');
console.log(proxy.display());
console.log(proxy.display());

Common Uses

  • Lazy loading
  • Virtual proxies for remote objects
  • Access control

When to Use

  • To add a layer of control or enhancement to an object
  • To defer object creation or expensive operations

Caution

  • Can introduce complexity
  • Not always obvious when proxy is being used