Proxy Pattern and Dynamic Proxies

|
| By Webner

Proxy pattern is about using proxy in front of another entity. It is a structural pattern, which means, it is implemented by changing/extending the structure of code.
One example of proxy classes is remote communication. In case of remote communication, proxy of remote object resides on client side. Purpose of this proxy is to shield the client from lower level network details (connecting to actual remote object/(un)marshalling of arguments etc.). Client code will use the remote object as if it were a local object because of the proxy in the middle. This type of proxy is called Remote Proxy.
There are many other types of proxies. More common of those are Virtual Proxy, Cache proxy and Protection Proxy.

Proxy pattern achieves its goal by having same method signatures in a proxy class as they are in actual class. So if we have a class Student, for which we need a proxy and Student class is as below:

class Student
{

String name;
int ageInYears;
String getName()
{
return name;
}

int getAge()
{
return ageInYears;
}

}

We can have a StudentProxy class like this:

class StudentProxy
{
Student student;
String getName()
{
return student.getName( );
}

int getAge()
{
return student.getAge( );
}

}

Better way to do it is to create a common interface/abstract class and have both Student and StudentProxy implement that.

interface StudentInterface
{
//body
}
class Student implements StudentInterface
{
//body
}
class StudentProxy implements StudentInterface
{
//body
}

Here, we know that StudentProxy implements StudentInterface. StudentProxy is static, which means it implements predefined interfaces. If we have an Employee class with same member variables as Student and few more, we will need to create an EmployeeProxy class to proxy Employee. Or we will have to make StudentProxy implement both StudentInterface and EmployeeInterface (which we should’nt be doing in real!!).

Dynamic Proxies are dynamic in the sense that they can implement interfaces dynamically. Theoretically speaking, that means we do not need to change StudentProxy class if we want to use it as proxy for Employee class as well. This is possible if we make StudentProxy a dynamic proxy.

For Java, JDK 1.3 onwards, there is an api for writing dynamic proxies (check reflection package).

Leave a Reply

Your email address will not be published. Required fields are marked *