Skip to content

Instantly share code, notes, and snippets.

@thonglinhma
Last active April 20, 2018 09:02
Show Gist options
  • Save thonglinhma/a465c63695ff822071b2b09793b1f442 to your computer and use it in GitHub Desktop.
Save thonglinhma/a465c63695ff822071b2b09793b1f442 to your computer and use it in GitHub Desktop.
abstract class State {
bool isAuthorized({Context context});
String userId({Context context});
}
class Context {
State _state = new UnauthorizedState();
bool get isAuthorized => _state.isAuthorized();
String get userId => _state.userId();
void changeStateToAuthorized({String userId}) {
_state = new AuthorizedState(userId: userId);
}
void changeStateToUnAuthorized() {
_state = new UnauthorizedState();
}
}
class UnauthorizedState extends State {
@override
bool isAuthorized({Context context}) => false;
@override
String userId({Context context}) {
return null;
}
}
class AuthorizedState extends State {
String _userId = null;
AuthorizedState({String userId}) : this._userId = userId;
@override
bool isAuthorized({Context context}) => true;
@override
String userId({Context context}) {
return _userId;
}
}
main(List<String> arguments) {
final userContext = new Context();
print(userContext.isAuthorized);
print(userContext.userId);
userContext.changeStateToAuthorized(userId: "admin");
print(userContext.isAuthorized);
print(userContext.userId);
userContext.changeStateToUnAuthorized();
print(userContext.isAuthorized);
print(userContext.userId);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment