Skip to main content

What does the Proxy pattern do?

Proxy is a structural pattern that creates a substitute object controlling access to another object. It behaves the same way as the original, but can add extra behavior, such as caching, security, logging, or lazy loading.


1. The Core Idea

The client does not work with the real object but with its "representative", the proxy. This proxy intercepts calls and decides whether to forward them to the real object or handle them itself.

In simple terms: Proxy is a "smart reference" to the real object.


2. When It Is Used

  • Access control - checking permissions before reaching a resource.
  • Lazy initialization - the object is created only on first use.
  • Remote access (Remote Proxy) - reaching an object on another server.
  • Caching - storing call results for reuse.
  • Protection or logging - adding layers of security or analytics.

3. Example (Java)

java
interface Image { void display(); } class RealImage implements Image { private String fileName; public RealImage(String fileName) { this.fileName = fileName; loadFromDisk(); } private void loadFromDisk() { System.out.println("Loading: " + fileName); } public void display() { System.out.println("Displaying: " + fileName); } } class ProxyImage implements Image { private RealImage realImage; private String fileName; public ProxyImage(String fileName) { this.fileName = fileName; } public void display() { if (realImage == null) realImage = new RealImage(fileName); realImage.display(); } }

Usage:

java
Image img = new ProxyImage("photo.jpg"); img.display(); // loads on the first call img.display(); // no loading the second time

4. Advantages

  • Controls and optimizes access to heavy or remote resources.
  • Lazy initialization saves memory and time.
  • Lets you add functionality without changing the original class.

5. Conclusion

Proxy is an intermediary object that substitutes for the real object, intercepts access to it, and controls access, execution, or caching, while staying transparent and interface-compatible for the client.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.