Skip to content

Instantly share code, notes, and snippets.

@saturngod
Created March 2, 2024 14:25
Show Gist options
  • Save saturngod/7ce5bd69dcf77d22195a9cc6fba02b03 to your computer and use it in GitHub Desktop.
Save saturngod/7ce5bd69dcf77d22195a9cc6fba02b03 to your computer and use it in GitHub Desktop.
public interface LoginStrategy {
public void login();
}
public class UsernamePasswordLogin implements LoginStrategy {
private String username;
private String password;
public UsernamePasswordLogin(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public void login() {
System.out.println("Logging in with username and password");
}
}
public class FacebookLogin implements LoginStrategy {
private FacebookAPI facebookAPI;
public FacebookLogin(FacebookAPI facebookAPI) {
this.facebookAPI = facebookAPI;
}
@Override
public void login() {
System.out.println("Logging in with Facebook");
}
}
public class LoginContext {
private LoginStrategy loginStrategy;
public void setLoginStrategy(LoginStrategy loginStrategy) {
this.loginStrategy = loginStrategy;
}
public void login() {
loginStrategy.login();
}
}
LoginContext loginContext = new LoginContext();
LoginStrategy usernamePasswordLogin = new UsernamePasswordLogin("user", "pass");
loginContext.setLoginStrategy(usernamePasswordLogin);
loginContext.login();
LoginStrategy facebookLogin = new FacebookLogin(new FacebookAPI());
loginContext.setLoginStrategy(facebookLogin);
loginContext.login();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment