Thursday, September 26

Proxy Design Pattern in Java, lazy loading using Proxy Design Pattern

                         Proxy Design Pattern in Java, lazy loading using Proxy Design Pattern

What is Proxy Design Pattern 

1. Proxy design patten works on the principal of exposing an Java Instance through a proxy instead of actual object. 

2. Client would never know anything about actual object and through Proxy only relevant behavior of actual object will be exposed to client.

3. Proxy Pattern can be used for applying security on actual Object. Service provider does not want actual class to be visible to any client Instead It would be shared as per Client contract agreement . Service provider may agree to share only a part of Service with it's client and for that It may expose a different contract in the form of interface in java . 





-->


4. This concept is very useful for lazily loading an instance . Data will be loaded only when it is actually required in an operation . Till then only proxy to Real instance will be kept as reference So as to invoke desired method later and retrieve the actual instance. 

I have tried to cover both these things directly through Java Code. 

Which class is doing what is directly written in System.out.println statement in each Class below . Executing the code will print all description on console.


Example 1.

This example covers How we can secure premium part of our Service from public cliewnts

public class ProxyClient {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ServiceProxy proxy = new ServiceProxy();
        System.out.println("Clients invokes the operation on ServiceProxy instance....");
        System.out
                .println("Here Client is invoking operation on Proxy Service only. It knows nothing about actual service. Thus using proxy of actual object");
        proxy.operate();
    }

}

class RealService implements IService {

    RealService() {

        System.out
                .println("Service Provider never wish to share the instance of this class to any client publicly as it contains some premium methods as well which are just for premium clients. So it wants to restrict the access of premium methods publicly");
    }

    public void operate() {
        System.out.println("this is the real operation where actual logic is executed......");
        System.out
                .println("This is a premium method . It should not be shared publicly. It is not exposed  through IService interface");
    }

    public void execute() {
        System.out
                .println("This is a premium method . It should not be shared publicly. It is not exposed  through IService interface");

    }

    public void serve() {
        System.out
                .println("This is a premium method . It should not be shared publicly. It is not exposed  through IService interface");

    }

}

// This is the contract which can be publicly shared to all the clients to access methods available for all public
interface IService {

    public void operate();
}

class ServiceProxy implements IService {

    ServiceProxy() {

        System.out
                .println("Service provider does not want to expose actual instance of RealService publicly to everyone. It will share that only with premium clients.So an proxy is created . This Proxy implement the all methods of interface that actual service implements. Now this proxy is available to all the client to invoke public method without even knowing about the actual instance");
    }

    public void operate() {

        System.out.println("Here proxyService is delegating the call to Actual service method....");
        System.out
                .println("Here call is delegated to actual service and actual logic is executed in actual service method only . Result returned from that is received in proxy instance and is sent back to client.This Client remains totally agnostic of Actual service and Just deal with Proxy Service to invoke operations available in real service.");
        IService service = new RealService();
        service.operate();
    }

}



This example will print on console :




---------------------------
 It is Just proxy of actual object. So on instantiation is created just empty object. Data will be lazily loaded on invocation of operate() method
Clients invokes the operation on ServiceProxy instance....
Here Client is invoking operation on Proxy Service only. It knows nothing about actual service. Thus using proxy of actual object
Here proxyService is delegating the call to Actual service method....
Here call is delegated to actual service and actual logic is executed in actual service method only . Result returned from that is received in proxy instance and is sent back to client.This Client remains totally agnostic of Actual service and Just deal with Proxy Service to invoke operations available in real service.
Actual Instance is created here. It execute database calls and provide a state to the Object

--------------------------- 


Example 2

This example covers how lazy loading works and implemented using Proxy Design Pattern 


package pkg;

public class Client {
    IService proxy;

    Client() {
        System.out
                .println("Here When instance is created it only associates the proxy with it. Proxy instance is created. But Actual Service is not constructed ");
        proxy = new ServiceProxy();
    }

    /**
     * @param args
     */
    public void invoker() {

        System.out
                .println("On invocation of operate() method on proxy real instance is created. So instance of stateful object is created only when it is actually required. Till that time client only keeps the proxy to actual object. This is the concept of lazy loading which is heavily used in lot of J2ee frameworks like Spring");
        proxy.operate();
    }

    public static void main(String args[]) {
        Client client = new Client();
        client.invoker();
    }

}

class RealService implements IService {
    DBObject object;

    RealService() {
        System.out
                .println("Actual Instance is created here. It execute database calls and provide a state to the Object");
        object = new DBObject();

        // JDBC Code is executed to provide a state to object.

    }

    public void operate() {
        // TODO Auto-generated method stub
        object.decorateObject();
    }

}

// This interface has no method but is very useful in implementing Lazy loading concept
interface IService {

    void operate();

}

class ServiceProxy implements IService {

    ServiceProxy() {

        System.out
                .println("It is Just proxy of actual object. So on instantiation is created just empty object. Data will be lazily loaded on invocation of operate() method");
    }

    public void operate() {

        System.out.println("Here proxyService is delegating the call to Actual service method....");
        System.out
                .println("Here call is delegated to actual service and actual logic is executed in actual service method only . Result returned from that is received in proxy instance and is sent back to client.This Client remains totally agnostic of Actual service and Just deal with Proxy Service to invoke operations available in real service.");
        IService service = new RealService();

    }

}

class DBObject {

    public void decorateObject() {

        System.out.println("data is fetched from DB to apply other attributes to the object");
    }

}

This example will print on console :

---------------------------
Here When instance is created it only associates the proxy with it. Proxy instance is created. But Actual Service is not constructed
It is Just proxy of actual object. So on instantiation is created just empty object. Data will be lazily loaded on invocation of operate() method
On invocation of operate() method on proxy real instance is created. So instance of stateful object is created only when it is actually required. Till that time client only keeps the proxy to actual object. This is the concept of lazy loading which is heavily used in lot of J2ee frameworks like Spring
Here proxyService is delegating the call to Actual service method....
Here call is delegated to actual service and actual logic is executed in actual service method only . Result returned from that is received in proxy instance and is sent back to client.This Client remains totally agnostic of Actual service and Just deal with Proxy Service to invoke operations available in real service.
Actual Instance is created here. It execute database calls and provide a state to the Object
---------------------------






Java State Design Patten , OOPS state design pattern

                                         Java State Design Patten , OOPS state design pattern







State Design Pattern 
 
State design pattern works on the concept of state change. Entire process life-cycle can be divided in multiple phases.With completion of each phase process exits from one state and enters in to another state. 

For example In JSF framework entire web request response lifecycle is divided in six phases:

1. RestoreViewPhase
2. ApplyRequestValuePhase
3. ProcessValidationPhase
4. UpdateModelvaluesPhase
5. InvokeApplicationPhase
6. renderResponsePhase


After completion of every phase process exits from a state and enters into another state. For example after RestoreValuePhase we can say ViewRestored as exit state and RequestApply as entering state . 

So to implement State design pattern It is required to divide entire process in such a way that It can be processed in multiple phases with every phase exit defining a state change. 

Now let's understand this with below code. 


Any project lifecycle can be divided in multiple phases like 


  • requirementAssessment
  • Design
  • Development
  • QualityAssessment
  • Deploy
  • Closure


So these are the phases used in below example 

Rules : 

1. We need to define a class where we can store the current state of the process. NextPhase class in below code is doing that.

2. We need to define an Interface wherein we can provide the contact method that would be implemented in each phase.In below code ProjectPhase is doing that.

3. For each phase we need to write a class implementing ProjectPhase interface. 

4. ProjectExpeditor is client class which basically utilize the design pattern features.


 Describing below Example
 When NextPhase instance is created in Client (ProjectExpeditor ) class it will set the initial state of the process. In below example first state is RequirementAssessment.
Then client code continues retrieving the Next phase and execute the common method on that. 
With every execution current state is changed to next state . This responsibility lies on implementing classes. In below code After business logic execution every class in calling setPhase() method of NextPhase class and sets the Next state. So next invocation from client would be on next state instance .

Client code will set an exit condition ,which is nothing but last phase of process , Closure phase in this example 



-->



   interface ProjectPhase{

   

      void act(NextPhase nextPhase);

   

   }

 

class NextPhase {



    ProjectPhase phase;



    public NextPhase() {

        this.phase = new RequirementAssessment();

    }



    public void setPhase(ProjectPhase phase) {

        this.phase = phase;

    }



    public ProjectPhase getPhase() {

       return this.phase;

    }

}

 

  class RequirementAssessment implements ProjectPhase{

     

      public void act(NextPhase nextPhase){

         

          System.out.println("requirement analysis is done......");

         

          nextPhase.setPhase(new Design() );

      }



  



  

  }

 

class Design implements ProjectPhase{

     

      public void act(NextPhase nextPhase){

         

          System.out.println(" Design is done......");

         

          nextPhase.setPhase(new Development()  );

      }



  



  

  }

class Development implements ProjectPhase{

   

    public void act(NextPhase nextPhase){

       

        System.out.println("Development is done......");

       

        nextPhase.setPhase(new QualityAssessment() );

    }









}

class QualityAssessment implements ProjectPhase{

   

    public void act(NextPhase nextPhase){

       

        System.out.println("Quality assessment is done......");

       

        nextPhase.setPhase(new Deploy() );

    }









}

class Deploy implements ProjectPhase{

   

    public void act(NextPhase nextPhase){

       

        System.out.println("Deployment is done......");

        

        nextPhase.setPhase(new Closure() );

    }





 }



class Closure implements ProjectPhase{

   

    public void act(NextPhase nextPhase){

       

        System.out.println("Project is closed....");

       

  }





 }


public class ProjectExpeditor {



    /**

     * @param args

     */

    public static void main(String[] args) {

       

        NextPhase nextPhase=new NextPhase();

        ProjectPhase projectPhase=nextPhase.getPhase();

      

        while(true){


         if(projectPhase instanceof Closure){

             break;

         }else{

             projectPhase=nextPhase.getPhase();

             projectPhase.act(nextPhase);

         }

        }

  

    }

   

  }




Executing above code will result :

 requirement analysis is done......
 Design is done......
Development is done......
Quality assessment is done......
Deployment is done......
Project is closed....


You can directly copy and execute this code to understand further.