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.).
It's quick, easy and you get access to all the articles on DevX.
This registration/login is to allow you to read articles on devx.com. Already a member?
To become a member of DevX.com create your Member Profile by completing the form below. Membership is free!
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.