Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Advanced
Jan 14, 1999

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 attributes
8. 
9.       public void aMethod () {
10.         s.aMethod();
11.    }
12. 
13.    // Other methods
14.   
15.  }
16. 
17. public class Server implements SomeIfc {
18. 
19.   // Class attributes
20.   public aMethod () {
21.     // Actual method implementation.
22.   }
23. 
24.   // Other methods
25. }
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.).

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.

Ajit Sagar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap