So I'm coding a simple IRC client in Java. As of now, I'm trying to determine what commands the us开发者_C百科er is typing in. I know I can use a bunch of if-else statements, but that's not very good practice. I thought of using a switch, but I'm trying to find an alternative to that.
For example: I have some commands, PASS, NICK, USER, JOIN, PART, MODE
and some example input from the user: NICK John
I can retrieve the input, but I want a clean, efficient way to be able to tell the program to call the method_nick(John), which would then send that to the server.
Just a point in the right direction would be appreciated. I'm just at a loss as to how to handle this without a switch/if-elses.
A good way to ommit if-else is to use switch-case ;)
You could use map with the command strings as a keys and a command object for the action. This is called the Command Pattern.
Map<String,Action> m=new Map<String,Action>();
m.put("NICK", new Action() { public void execute() {... } });
m.put("PASS", new Action() { public void execute() {... } });
and then:
m.get(command_from_irc).execute();
Another approach is to use reflection.
精彩评论