Created
March 2, 2024 14:25
-
-
Save saturngod/7ce5bd69dcf77d22195a9cc6fba02b03 to your computer and use it in GitHub Desktop.
This file contains 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
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(); | |
} | |
} |
This file contains 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
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