Course contentsShow
← JavaScript
Lesson 1848 of 2,72338. Object-Oriented PatternsFree lesson

The Proxy Pattern

Provide a surrogate or placeholder to control access to another object, adding logic like caching.

The Proxy Pattern

You'll learn how to use a proxy object to control and extend access to another object without changing its code.

What Is the Proxy Pattern?

The Proxy Pattern creates an intermediary object that sits between a client and a target object. This "middleman" controls access to the target, allowing you to add extra logic like validation, caching, logging, or lazy initialization—all without modifying the original object.

Think of it like a personal assistant: instead of speaking directly to a busy executive (the real object), you communicate through the assistant (the proxy), who handles scheduling, filters requests, and may even answer questions from memory without bothering the executive.

Core Implementation

class ExpensiveAPI {
  fetchData(id) {
    console.log(`Fetching data for ID: ${id}...`);
    // Simulate expensive operation
    return { id, data: `Result for ${id}` };
  }
}

class CachingProxy {
  constructor(api) {
    this.api = api;
    this.cache = {};
  }

  fetchData(id) {
    if (this.cache[id]) {
      console.log(`Returning cached result for ID: ${id}`);
      return this.cache[id];
    }

    const result = this.api.fetchData(id);
    this.cache[id] = result;
    return result;
  }
}

const api = new ExpensiveAPI();
const proxy = new CachingProxy(api);

proxy.fetchData(1); // Fetches and caches
proxy.fetchData(1); // Returns from cache
proxy.fetchData(2); // Fetches new data

The proxy maintains the same interface as the original object (fetchData), so clients use it identically. The caching logic is added transparently—the proxy intercepts calls, checks its cache, and only forwards requests to the real object when necessary.

Key Takeaway: The Proxy Pattern adds a control layer around an object, enabling features like caching, validation, or lazy loading without altering the original object's implementation.