Created
October 12, 2014 17:34
-
-
Save MagicMicky/3ab6327b111db65ed340 to your computer and use it in GitHub Desktop.
An example showing the Adapter Design pattern, adapted to some account authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* We want to auth our user on an application. | |
* We have two way to auth our user. | |
* We can either authenticate the user using his mail and password via Google, thanks to the Google SDK | |
* Or we can use the Facebook SDK to auth our user. | |
*/ | |
public GoogleAuthenticator() { | |
public String authenticateViaGoogle(String mail, String password) { | |
//Android code | |
} | |
} | |
public FacebookAuthenticator() { | |
public boolean authenticateViaFacebook(String mail, String password) { | |
//Facebook code | |
} | |
} | |
/* | |
* Now, we want to be able to either authenticate the user using facebook, or using his mail. | |
* We need to create... | |
* SOME ADAPTERS ! | |
*/ | |
public interface AuthenticationAdapter() { | |
/* | |
* -1 if an error happened; 0 if user is authenticated. | |
*/ | |
int authUser(User u); | |
} | |
/* | |
* Our implementation of our adapter for a Google authentication | |
*/ | |
public class GoogleUserAuthenticationAdapter() implements AuthenticationAdapter{ | |
private GoogleAuthenticator auth; | |
public GoogleUserAuthenticationAdapter() { | |
this.auth = new GoogleAuthenticator(); | |
} | |
public int authUser(User u) { | |
String s = auth.authenticateViaGoogle(u.getEmail(), u.getPassword()); | |
if(s=="error") | |
return -1; | |
return 0; | |
} | |
} | |
/* | |
* Our implementation of our adapter for a Facebook authentication | |
*/ | |
public class FacebookUserAuthenticationAdapter() implements AuthenticationAdapter{ | |
private FacebookAuthenticator auth; | |
public GoogleUserAuthenticationAdapter() { | |
this.auth = new FacebookAuthenticator(); | |
} | |
public int authUser(User u) { | |
boolean b = auth.authenticateViaFacebook(u.getEmail(), u.getPassword()); | |
if(b==false) | |
return -1; | |
return 0; | |
} | |
} | |
/* | |
* Now, we can have our client that work with our adapter... | |
* We simply need to get him the right adapter when creating our AuthenticateRequest. | |
*/ | |
public class AuthenticateRequest { | |
private AuthenticationAdapter mAuthAdapter; | |
public AuthenticateRequest(AuthenticationAdapter authAdapter) { | |
this.mAuthAdapter = authAdapter; | |
} | |
public void authUser(User u) { | |
mAuthAdapter.authUser(u); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment