Course contentsShow
← Software Engineering
Lesson 277 of 1,9338. Structural Design PatternsFree lesson

Proxy Pattern: Controlling Access to Objects

Understand how the Proxy pattern provides a surrogate or placeholder to control access to another object.

Proxy Pattern: Controlling Access to Objects

What you'll learn: How the Proxy pattern acts as a gatekeeper to control how and when you access another object.


The Core Idea

The Proxy pattern provides a surrogate or placeholder that stands in front of another object and controls access to it. Think of it like a security guard at a building entrance—you don't directly access the building; instead, you interact with the guard who decides whether to let you through, checks your credentials, or logs your entry.

The proxy and the real object share the same interface, so clients interact with the proxy exactly as they would with the real object. The proxy forwards requests to the real object when appropriate, but can add extra behavior before or after forwarding.

Why Use a Proxy?

Proxies solve several problems:

  • Access control: Check permissions before allowing operations
  • Lazy initialization: Delay creating expensive objects until actually needed
  • Logging/monitoring: Track how and when an object is accessed
  • Remote access: Represent an object that exists elsewhere (different process or machine)
  • Caching: Store results to avoid repeated expensive operations

Real-World Analogy

Imagine a library reference desk. You can't directly access rare books in the vault. Instead, you tell the librarian (proxy) what you need. The librarian checks if you have proper credentials, logs your request, retrieves the book from the vault (lazy loading), and may even remember which books were recently requested (caching).

Key Takeaway: The Proxy pattern wraps an object with a surrogate that controls access, adding protective, performance-enhancing, or monitoring behavior without changing how clients interact with the object.