We are developing an enterprise application. You are responsible for authentication module. But you are not sure how you are going to do authentication. You can have authentication against LDAP, database or any other centralized directory. So you first define an interface for authentication with single method authorize() This method returns true if user is successfully authenticated or false if not authenticated.
public interface UserAuthentication {
public boolean authorize();
}
Let us create a class which authenticate against users table in database using JDBC.
public class JDBCUserAuthentication implements UserAuthentication {
@Override
public boolean authorize() {
boolean result=false;
// implementation for authentication using JDBC
//if authenticated
//result=true
//else
//result=false
return result;
}
}
Similarly another class which authenticate against LDAP.
public class LDAPUserAuthentication implements UserAuthentication {
@Override
public boolean authorize() {
boolean result=false;
// implementation for authentication using LDAP
//if authenticated
//result=true
//else
//result=false
return result;
}
}
Well, now we have two implementations, one using JDBC and another using LDAP. Now let us create factory class.
public class UserAuthenticationFactory {
public static UserAuthentication getUserAuthentication(String type){
if (type.equalsIgnoreCase("jdbc")){
return new JDBCUserAuthentication();
}else if(type.equalsIgnoreCase("ldap")){
return new LDAPUserAuthentication();
}else{
return new JDBCUserAuthentication();
}
}
}
In the above class we define a static method getUserAuthentication() which instantiates appropriate sub class based on parameter.
When you do authentication your code snippet may be as follows.
//declare isAuthorized variable
boolean isAuthorized=false;
//get UserAuthentication object
UserAuthentication userAuthentication=
UserAuthenticationFactory.getUserAuthentication("jdbc");
isAuthorized=userAuthentication.authorize();
if(isAuthorized){
//redirect to home page
}else{
//redirect to login page
}
I hope you got enough clarity about factory method pattern and its implementation in practical scenario.
No comments:
Post a Comment