C++ Custom GUI Button Question


I am designing a graphical application for which I've decided to write my own menu. I would like this menu to be platform independent. For the time being, my menu will mostly consist of a number of buttons. My issue involves the handling of events when a button is clicked. My dilemma is with a button "knowing" about the context in which it exists. It seems to me that if there is some larger piece of code that creates buttons and handles mouse events, the need for some type of switch statement might arise. The switch statement would have to invoke the appropriate action based on whatever uniquely defined the button that was clicked.

I would like to avoid this switch statement. My first idea was to have each button maintain a function pointer that it uses to blindly initiate the correct action when it is clicked. This would eliminate any button-specific code. Yet, it bugs me that a button should contain any context-specific information (such as a function pointer). I am fairly inexperienced and I am wondering if this is considered bad design. Regardless, how can I design my menu in a manner which eliminates the need for some type of switch statement and is considered good OOP design? I would like to hear what your preferred solutions are.

Thanks in advance!

Best Solution

You can take a look at the Command Pattern.

You can associate a command to a menu item, the command would contain the code to be executed.

Related Question