views:

780

answers:

2

Hello!

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!

+2  A: 

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.

Megacan
Thanks, this worked perfectly.
Scott
+4  A: 

You take a look at libraries :
SPTK
http://www.sptk.net/index.php SPTK (Simply Powerful Toolkit) is a cross-platform toolkit that provides a set of C++ classes for fast and easy application development. It provides GUI components that use FLTK, and features database support with seamless connection to GUI components.

eGUI
http://www.codeplex.com/egui
http://torjo.com/egui/
http://msdn.microsoft.com/en-us/magazine/cc534994.aspx

NovaTK
http://novatk.sourceforge.net
NovaTK is an object-oriented, cross-platform GUI toolkit. One of the focuses of NovaTK is to facilitate rapid development of cross-platform applications requiring fewer lines of code. The event system is based upon a powerful callback mechanism that makes application design simpler, easier to read, and logical.

Ecere Cross Platform GUI Applications
http://www.ecere.com
Develop applications once, deploy them on all platforms alongside a lightweight runtime environment.

Introduction to wxWidgets
http://www.codeproject.com/KB/library/wxwidgets.aspx

ClassLib, A C++ class library
http://www.codeproject.com/KB/library/classlib.aspx

lsalamon