1

I want to implement some kind of Command Pattern in Java. I want to have a structure like Map<String commandkey, Function()>. So I have an object (Map, HashMap, LinkedHashMap or whatever associative...) where keys are string commands and values are functions which i want to call by the key. These functions have to be heterogeneous in the sense the can have different return values, number of parameters, names (different signatures). In C++ e.g. I can create a Map of function pointers or functors via boost::function. So can someone name all the ways of implementing such an idiom (or a pattern if we look at it in broad sense) in Java. I know two ways:

  1. Reflection (minus: slow and very ugly)
  2. Using an interface and anonymous classes (minus: functions must have the same signature)

Detail explanation, links to articles and so on will be very helpful.

Oleksandr Karaberov
  • 12,573
  • 10
  • 43
  • 70
  • It's hard to say as we don't know how you want to use the API, but it sounds like your design isn't really Object-oriented... Consider to revise your design. – Puce Mar 01 '13 at 14:17
  • @Puce "your design isn't really Object-oriented".If you read my question more attentively you will see that I didn't say a word about OO design.I want to implement a Function pattern which is more related to functional design and FD patterns. I'm interesting how can java handle such multiparadigmality – Oleksandr Karaberov Mar 01 '13 at 14:22
  • Yeah, but you mentioned Java - and Java is an Object-oriented language and thus it's usually recommended to follow an Object-oriented design. – Puce Mar 01 '13 at 14:29

1 Answers1

5
  1. there are no function pointers in java, only interfaces
  2. imo reflection is not as slow and ugly as many people think
  3. you still need to know how to call the function (you need to know that in c++ too) so having the same signature is not that bad, just take a very flexible signature like void command(Object... args)

Edit: about Reflection performance: look at this threads answer: Java Reflection Performance

you can see that just calling a reflection object is not that slow, it's the lookup by name that costs alot of time, and i think i your case you dont need that more than once per function

Community
  • 1
  • 1
x4rf41
  • 5,184
  • 2
  • 22
  • 33
  • its always "reflection is so slow and dirty", but the people saying that never do the performance tests. also its imo not "dirty" since you can do thing with them that arent possible in other ways. plus with @annotations you can do alot of really cool stuff. – x4rf41 Mar 01 '13 at 14:34
  • So true. I recently used reflection to make a dynamic object replication library and the performance is really good. Of course, it has its penalties in certain situations but since it is not intended to be used on such scenarios (performance critical scenarios, to be specific), it shouldn't get the hate. It's a programmer's decision after all. – Fritz Mar 01 '13 at 14:37