How does the Proxy pattern work in Java

The Proxy pattern is a structural design pattern that allows you to provide a surrogate or placeholder for another object to control access to it. In Java, it is often used to control access to an object that is resource-intensive to create or where access should be restricted for security reasons.

How the Proxy Pattern Works

The Proxy pattern involves three main components:

  • Subject: This is the interface that both the RealSubject and Proxy implement.
  • RealSubject: This is the actual object that the Proxy represents. It performs the real operations.
  • Proxy: This class contains a reference to the RealSubject and controls access to it, adding additional functionality such as lazy initialization, access control, or logging.

Example of Proxy Pattern in Java

// Subject interface interface Subject { void request(); } // RealSubject class class RealSubject implements Subject { @Override public void request() { System.out.println("RealSubject: Handling request."); } } // Proxy class class Proxy implements Subject { private RealSubject realSubject; @Override public void request() { if (realSubject == null) { realSubject = new RealSubject(); } // Additional functionality can be added here if necessary realSubject.request(); } } public class Client { public static void main(String[] args) { Subject proxy = new Proxy(); proxy.request(); // First call, creates RealSubject proxy.request(); // Second call, uses cached RealSubject } }

proxy pattern java proxy pattern design patterns in java structural design patterns java programming