Sunday, 24 April 2016

Proxy design pattern

Proxy design pattern

This design pattern is uses a proxy class to have a controlled access to a particular class.
E.g. If a certain class initialization is very costly, we can tie it up to a proxy class. Proxy class can be used to lazily initialize the target class.
There are 4 types of proxy classes.
1.     Cache proxy:
In this case if a result is computed for 1 call from the client, the same can be cached and served as response to another call by another client.
2.     Protection proxy:
If we require having some kind of authentication before accessing the target class, use a proxy class and do the authentication there before calling the target class.
3.     Remote proxy:
If the target class is remotely available, use the proxy class to make the calls over the network and handle the response. The client remains unaware and thinks that the response is generated locally.
4.     Smart proxy:
It can be used for conditional handling of the requests. E.g. if the target class (resource) is very busy, the proxy can identify this and can deny/delay the new processing request by the client. It can maintain a reference count to the number of calls to the resource class & can interpret whether the resource is busy or not.


public interface IResource {
      public String execute();
}

public class DatabaseResource implements IResource {

      @Override
      public String execute() {
            return "Calling the database at --> "+new Timestamp(System.currentTimeMillis());
      }

}
public class CacheProxy implements IResource {
     
      String response = null;

      @Override
      public String execute() {
            System.out.println("Calling cache proxy");
            if(response == null) {
                  response = new DatabaseResource().execute();
            } else {
                  System.out.println("Response from cache");
            }
            return response;
      }

}

public class MainClass {

      public static void main(String[] args) {
            IResource resource = new CacheProxy();
            System.out.println(resource.execute());
            System.out.println(resource.execute());
      }


}


Code link : https://github.com/sksumit1/DesignPatterns

No comments:

Post a Comment