Using Proxy Classes in Java

Using Proxy Classes in Java

The Proxy is one of the most common design patterns in circulation. Gamma et. al. define the intent of the Proxy as: “Provide a surrogate or a placeholder for another object to control access to it.” The basic idea is that a class substitutes for another class. In other words, a Proxy class provides an interface that reflects the interface of the class that it is substituting. In Java, a Proxy class must implement the same interface as the class that it is substituting.

A Proxy is usually associated with a client-server paradigm. The Server and the Client classes implement the same interface. However, the Client only implements stubs of methods where as the Server provides the actual implementations for the methods specified in the interface. For example:

 1.     public interface SomeIfc {2.       public void aMethod();3.     }4. 5.     public class Client implements SomeIfc {6.       Server s = new Server();7.       // Other attributes8. 9.       public void aMethod () {10.         s.aMethod();11.    }12. 13.    // Other methods14.   15.  }16. 17. public class Server implements SomeIfc {18. 19.   // Class attributes20.   public aMethod () {21.     // Actual method implementation.22.   }23. 24.   // Other methods25. }

Lines 1-3 define an interface called SomeIfc. It defines a single method called aMethod(). Both the Client class (Lines 5-15) as well as the Server class (Lines 17-25) implement the interface SomeIfc. This ensures that aMethod() is available to the application that uses the Client class. On Line 6, the Client instantiates a new object of the type Server. In a real application, the code on Line 6 would be replaced by code that gets the Client a reference to the Server across some transport mechanism (like CORBA, sockets, RMI, etc.).

See also  How to Create and Deploy QR Codes Online: A Comprehensive Guide

Any call made to aMethod() on the Client is “delegated” to the Server. An application using the Client class is shielded from the knowledge that there is a Server in the picture. The Client acts as a Proxy to the Server. All access to the Server is only available via the Client.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist