Java - Function on the basis of a string

Associate
Joined
14 Jun 2009
Posts
668
Would prefer to avoid an unwieldly if/else block where possible. I'm something of a Java noob so bear with me here. :p

I need to execute a different function that is defined by a string (ie, if I find that the string is "ban" it should execute my banUser() function).

I know I could do this with a selection block but it seems neater to map them together as that way I can just go through the entire list of commands (and not worry about adding extra statements in the selection block when it comes to future expansion).

I've used languages like Lua which have fairly obvious interfaces for this but I can't find an equivalent in Java for mapping a string to a function.

Any help is much appreciated. :)
 
You could use the Strategy design pattern.

Basically you create your strategy interface then have some classes implement the method to handle the command so they might have an execute method. You make a concrete strategy for each command and place them all into a HashMap<string, strategy="">.

After that all you need is some code to parse your text to isolate the commands, lookup the HashMap for the instance of the Strategy that you need to execute for that command and call the method.

http://en.wikipedia.org/wiki/Strategy_design_pattern
:D

Learnt a new pattern and got it working. Thanks a lot. :)
</string,>
 
Back
Top Bottom