Showing posts with label OOPS design pattern. Show all posts
Showing posts with label OOPS design pattern. Show all posts

Friday, September 27

Java :: Adaptor Design pattern.

                                                          Adaptor Design pattern.




What is Adaptor

Adaptor is used to make tow parties talk with each otherwise could not talk as their communication channel is not compatible with each other

For Example :

Adaptor for a mobile charger : Mobile can not be directly plugged in to electric socket to charge it . It between it requires an adaptor to to get connected. Adaptor converts 220V from electric socket to 9V what Mobile is made to accept .

An interpreter between two people talking two different languages unknown to each other. Interpreter acts as adaptor here.

Let me take you through java code How we can easily implement and use this pattern in java.

A class A has a method m which takes two parameters String ,String But client who wants to invoke that method does not have a pair of strings but has a Map . So how will they talk . We will insert one more class between then which will act as adaptor . It will take input from client ,will covert the Map parameters in String,String pair combinations and will call the class A method m . Thus client and service class A are not talking with each other directly and Adaptor is making their communication possible.

Here is example with java code . I have written are steps in system.out.println statements in methods. Executing then will print all logical steps on console. So copy this code and Execute .


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








This is the client class which has a Map with it But want to invoke execute of service class which expects a pair of String. So it can't call Service class directly Instead it invokes execute method in Adaptor class



package adaptor;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Client {

    /**
     * @param args
     */
    public static void main(String[] args) {

        IAdaptor adaptor = new Adaptor();
        Map map = new LinkedHashMap();
        map.put("Client", "Calling adaptor");
        map.put("adaptor", "redirecting request to service");
        map.put("service", "returning results to adaptor");
        map.put("then adaptor", "returns result to Client");
        map.put("Client and", "adaptor are compatible");
        map.put("Client has", "HashMap ,Service execute() method expects String ,String parameters");
        map.put("so client", "is incompatible to call service directly");
        map.put("adaptor has",
                "execute() method parameters as HashMap , So makes client compatible to call adaptor");
        map.put("further adaptor",
                "transform the input parameter and covert it in format as expected by service");
        map.put("thus", "Client execute service execute() method with the intervention of adaptor");
        map.put("adator class", "Acts as adaptor here to make Client call Service.");
        adaptor.execute(map);

    }

}

Interface For Adaptor Class that defines the execute method signature
interface IAdaptor {

    void execute(Map map);
}

Adaptor Class . It takes parameter from client ,transform the input in parameters expected by service class and then execute service class method
class Adaptor implements IAdaptor {
    IService service;

    public void execute(Map map) {
        service = new Service();

        Set set = map.entrySet();
       
        System.out.println("let us print all key value pairs");
        System.out.println("=======================================");

        for (Object object : set) {

           Entry entry=(Entry)object;

            service.execute(entry.getKey().toString(), entry.getValue().toString());

        }

    }
}

Interface for service class
interface IService {
    public void execute(String key, String value);
}

Service class .It has the acutal method that execute the required logic and It expects the parameter as String,String
class Service implements IService {

    public void execute(String key, String value) {
       
        System.out.println(  key + "--->  " + value);

    }

}





-->


Let Us see the output now
=======================================
Client--->  Calling adaptor


adaptor--->  redirecting request to service


service--->  returning results to adaptor


then adaptor--->  returns result to Client


Client and--->  adaptor are compatible


Client has--->  HashMap ,Service execute() method expects String ,String parameters


so client--->  is incompatible to call service directly


adaptor has--->  execute() method parameters as HashMap , So makes client compatible to call adaptor


further adaptor--->  transform the input parameter and covert it in format as expected by service


thus--->  Client execute service execute() method with the intervention of adaptor


adator class--->  Acts as adaptor here to make Client call Service.


Thursday, September 26

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.