Mapping polymorphic classes

I have an existing command line interface application to which I am adding a GUI. Often a situation arises when I have a list of objects that inherit from one class, and they need to be displayed in the list, but each subclass has a slightly different way of displaying.

Not wanting to have giant switch statements around the world, using reflection / RTTI to display, each class knows how to return its summary string, which is then displayed in a list:

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

Similar functions exist to display various information in different contexts. This was fine and good, until we needed to add a graphical interface. The line is no longer sufficient - I need to create graphical controls.

I don’t want to change every single class so that it can be displayed in the graphical interface - all the more so since there is at least one other GUI platform that we want to transfer.

Is there any technique I can use to separate this GUI code from data objects without resorting to RTTI and switch statements? It would be nice to get GetSummary functions as well.

Ideally, I could have a hierarchy of display classes that could take a data class and display them based on runtime type instead of 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); 
+4
source share
1 answer

I do not think this will solve your problem: you do not need to write code, but you should be able to abstract the GUI logic from data objects.

Look at the visitor’s template ( 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 on the platform.

+6
source

All Articles