Skip to content

Instantly share code, notes, and snippets.

@arianvp
Created September 27, 2014 15:19
Show Gist options
  • Save arianvp/a13170bb5c0664f5ba22 to your computer and use it in GitHub Desktop.
Save arianvp/a13170bb5c0664f5ba22 to your computer and use it in GitHub Desktop.
import java.io.Console;
interface Context {
State state();
void state(State state);
Console console();
}
interface State {
boolean process(Context ctx);
}
enum CommandLineStates implements State {
LOGIN {
public final boolean process(Context ctx) {
System.out.print("enter password:");
char[] password = ctx.console().readPassword();
for (int i = 0; i < password.length; i++) {
if (PASSWORD[i] != password[i]) {
return false;
}
}
ctx.state(ECHO);
return true;
}
},
ECHO {
@Override
public final boolean process(Context ctx) {
String a = ctx.console().readLine();
if (a == null) {
return false;
}
System.out.println(a);
return true;
}
};
private final static char[] PASSWORD = { 'a', 'r', 'i', 'a', 'n' };
}
final class CommandLineContext implements Context {
private State state;
private final Console console;
public CommandLineContext() {
this.state = CommandLineStates.LOGIN;
this.console = System.console();
}
@Override
public final State state() {
return state;
}
@Override
public final void state(State state) {
this.state = state;
}
@Override
public final Console console() {
return console;
}
}
public final class CommandLine {
private final Context context;
public CommandLine() {
this.context = new CommandLineContext();
}
public final void run() {
while (context.state().process(context))
;
}
public static final void main(final String[] args) {
new CommandLine().run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment