I am creating buttons dynamically for a user-based app. Now I have to tell the new form what text to apply to the buttons via parameters to the form, the form then creates the buttons. Now I have an issue – the events for these buttons: What is the best mechanism to get the button click events through. I cannot access the form from the originating form, and I can only pass simple data types (and arrays).
My first thought is to use a code to reffer to the appropriate method in a static class – basically, pass an array of ints through with the names of the buttons and their onclick handler calls one method – handle(int code) -> where code is used in a giant switch statement to call the appropriate method.
But I doubt this is the best mechanism. I would prefer to create a listener of some sort that simply listens for button clicks, and should the click be unhandled, determine which button was clicked and manage it from there.
I have looked at the observer pattern and I am not entirely convinced this is the best one to follow. The problem is not that there is no solution, the problem is that I want the BEST solution.
This is in C# for monodroid – but the impact of this information should be minimal.
Thanks
Currently I have two options:
Use reflection – pass a method name to the button and that button can then invoke a method based on the string value passed. Then simply create a static class where all button methods are kept.
Use a switch statement – since I can have delegates that take parameters (one of them being a SENDER object) I can easily send the sender object to a method containing a switch statement which performs an action based on that object.
In my research I have determined that the former (reflection) is preferred, espcially since the number of buttons is rather large.
REFS:
http://embeddedgurus.com/stack-overflow/2010/04/efficient-c-tip-12-be-wary-of-switch-statements/
Large Switch statements: Bad OOP?
Method Factory – case vs. reflection