Wednesday, December 13, 2017

Strategy Pattern

Definition -

    This is a pattern where in the client can choose among the options available to perform a specific task.
   
Scenario -
   
    Lets take a scenario where in you want the user to login via either forms authentication or google or facebook id. In this case you can apply the strategy pattern where in the same task of authentication is done but the method by which the authentication is done is different.
   
Based on the above -
1) We will have an interface called iauthenticate with a function called authenticateuser.

package StrategyPattern;

public interface iauthenticate {
    
    
    public boolean authenticateuser();

}

2) We will have two concrete classes called formsauthentication and googleauthentication.
formsauthentication.java
 
package StrategyPattern;

public class formsauth implements iauthenticate{

    String user;
    String password;
    
    public formsauth(String usr, String pwd) {
        this.user=usr;
        this.password=pwd;
    }
    
    @Override
    public boolean authenticateuser() {
        String pwd=getauthdetails(this.user);
        if(pwd==this.password) {
            return true;
        }
        else {
            return false;
        }
        
    }

    
    public String getauthdetails(String user) {
        
        return "*******";
        
    }

}


googleauthentication.java
package StrategyPattern;

public class googleauthentication implements iauthenticate {

    
    String user;
    String token;
    
    public googleauthentication(String usr,String tkn) {
        this.user=usr;
        this.token=tkn;
    }
    
    public String getauthdetails(String user) {
        //get the token from google
        return "axr4550313djrldoepcvjrmvrortjvlr";
    }

    @Override
    public boolean authenticateuser() {
        String temptkn=getauthdetails(this.user);
        if(this.token==temptkn) {
            return true;
        }
        return false;
    }

}



3) We will have a class called strategydemo which will have the option chosen by the user to authenticate and gain access into the system.
 
package StrategyPattern;

public class Strategydemo {
    
    public static void main(String args[]) {
        
        iauthenticate ia=null;
        String authtype="forms";
        
        if(authtype.equalsIgnoreCase("forms")) {
            ia=new formsauth("user1","*******");
        }else if(authtype.equalsIgnoreCase("Google")) {
            ia=new googleauthentication("user1","axr4550313djrldoepcvjrmvrortjvlr");
        }
        
        if(ia.authenticateuser()) {
            System.out.println("Authentication successful");
        }
        
    }

}



Place to use -
1) When you want to choose a technique to perform a functionality but you want to provide flexibility in terms how this can be achieved.


The code used above is present in the link here

No comments:

Post a Comment