views:

203

answers:

1

I have an existing app with a command-line interface that I'm adding a GUI to. One situation that often comes up is that I have a list of objects that inherit from one class, and need to be displayed in a list, but each subclass has a slightly different way of being displayed.

Not wanting to have giant switch statements everywhere using reflection/RTTI to do the displaying, each class knows how to return its own summary string which then gets displayed in the list:

int position = 0;
for (vector<DisplayableObject>::const_iterator iDisp = listToDisplay.begin(); iDisp != listToDisplay.end(); ++iDisp)
    cout << ++position << ". " << iDisp->GetSummary();

Similar functions are there to display different information in different contexts. This was all fine and good until we needed to add a GUI. A string is no longer sufficient - I need to create graphical controls.

I don't want to have to modify every single class to be able to display it in a GUI - especially since there is at least one more GUI platform we will want to move this to.

Is there some kind of technique I can use to separate this GUI code out of the data objects without resorting to RTTI and switch statements? It would be nice to be able to take out the GetSummary functions as well.

Ideally I'd be able to have a heierarchy of display classes that could take a data class and display it based on the runtime type instead of the compile time type:

shared_ptr<Displayer> displayer = new ConsoleDisplayer(); 
// or new GUIDisplayer()

for (vector<DisplayableObject>::const_iterator iDisp = listToDisplay.begin(); iDisp != listToDisplay.end(); ++iDisp)
    displayer->Display(*iDisp);
+6  A: 

I don't think this will solve your problem of not needing to write the code, but you should be able to abstract the GUI logic from the data objects.

Look at a Visitor pattern (http://en.wikipedia.org/wiki/Visitor_pattern) it will allow you to add code to an existing object without changing the object itself. You can also change the visitor based on the platform.

Dan Williams
Well obviously the code needs to be written - it's more an issue of having to clutter up the classes with functions that I believe should be somewhere else.
Eclipse
The visitor pattern looks very much like what I'm looking for - I'll take a deeper look at it.
Eclipse
Yeah, sorry, I didn't mean it to sound like that :)
Dan Williams
Thanks - that's exactly what I was hoping for!
Eclipse