Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Chain of Responsibility - GoF Way
abstract class Authenticator {
private Authenticator next;
public static Authenticator chain() {
Authenticator defaultMethod = new EmailAuthenticator();
Authenticator networkMethod = new NetworkAuthenticator();
defaultMethod.setNext(networkMethod);
Authenticator partnerMethod = new PartnerAuthenticator();
networkMethod.setNext(partnerMethod);
return defaultMethod;
}
public void setNext(Authenticator auth) { this.next = auth; }
public boolean login(String username, String password) {
if (canAuthenticate(username, password)) {
return authenticate(username, password);
}
if (next == null) {
return false;
}
return next.login(username, password);
}
abstract boolean canAuthenticate(String username, String password);
abstract boolean authenticate(String username, String password);
}
class EmailAuthenticator extends Authenticator {
public boolean canAuthenticate(String username, String password) {
return username.indexOf("@") > 0;
}
public boolean authenticate(String username, String password) {
// do email authentication
return true;
}
}
public class HellYeahController {
public void loginAction(Request request, Response response) {
boolean userLoggedIn = UserAuthenticator.login(
request.getParameter("username@foo.com"),
request.getParameter("password1")
);
if (userLoggedIn) {
System.out.println("WOW!");
} else {
System.out.println("OH NO!");
}
}
}
class NetworkAuthenticator extends Authenticator {
public boolean canAuthenticate(String username, String password) {
return username.indexOf("/") > 0;
}
public boolean authenticate(String username, String password) {
// do network authentication
return true;
}
}
class PartnerAuthenticator extends Authenticator {
public boolean canAuthenticate(String username, String password) {
return username.startsWith("/") && username.length() > 12 && username.endsWith("@");
}
public boolean authenticate(String username, String password) {
// do far away partner authentication
return true;
}
}
class Request {
public String getParameter(String key) { return key; }
}
class Response {}
class UserAuthenticator {
public static boolean login(String username, String password) {
return Authenticator.chain().login(username, password);
}
}
@hlegius

This comment has been minimized.

Copy link
Owner Author

hlegius commented Oct 27, 2013

There is more LOC than POG version, but this one is more testable; extensible; readable and will keep you employed. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.