Proxy

Category

Structural pattern

Problem

Provide a surrogate or placeholder for another object to control access to it. Useful when direct access is inappropriate due to cost, security, or complexity.

Solution

  • Create a proxy class that implements the same interface as the real subject
  • The proxy controls access to the real subject, adding its own behavior
  • The proxy can lazily initialize, cache, or add security checks

Structure

  • Subject: Interface for both RealSubject and Proxy
  • RealSubject: The actual object the proxy represents
  • Proxy: Holds a reference to RealSubject; controls access; adds functionality
  • Client: Uses Subject interface; doesn’t know it’s using a Proxy

Key Benefits

  • Controlled access — Can add security, caching, or lazy initialization
  • Transparency — Client interacts with the proxy as if it were the real object
  • Remote access — Proxies enable access to objects in different address spaces

Trade-offs

  • Adds an extra layer that can introduce performance overhead
  • Can become complex with multiple proxy types

When to Use

  • You need a more controlled or sophisticated reference to an object than a simple pointer
  • You want to lazy-load expensive objects
  • You need to add caching, logging, or access control

Examples