PDA

View Full Version : I need a design pattern


Backov
10-18-2007, 01:27 PM
I am trying to clean up my GUI library for Ogre prior to releasing it as open source. One of the cleanups I need to do is the way that controls are instantiated from XML, and I can't think of a great way to do this (in C++).

Basically the controls are in XML as you'd expect, with a "type" attribute being passed along from the control definition telling us what type of control it is. That boils down to an ugly if..then...else for each control type, even though they're all the same base type.

There's some special behavior, for instance, radio controls have to be added to their radio group after they're created, but almost everything else is the same.

What's the nice way to do this? In Java I could use reflection (I think that's what it's called) to do it pretty nicely, but I have no idea what a good way to do this in C++ is.

The other reason I want to find a nicer way to do this is because the current version of the GUI doesn't even have a way to instantiate controls into a sheet without XML, so I want to make a nice consistent interface that the loader and the coder can use at the same time.

I know there's some pattern geniuses here. Any insights?

zoombapup
10-18-2007, 02:05 PM
youre basically talking about a "Factory" pattern. Pass it the control definition and it returns the newly constructed control.

It really depends if you want to return a newly constructed control from the factory (which you then insert into your control heirarchy) or wether you want to pass the factory method a control heirarchy and a control definition and have it return a new control heirarchy (with control added to it).

I've written HTML style browser control interfaces where we had an abstract control constructor object (one per unique control type) and simply called that from the factory method based on a lookup table.

In the end, I wouldnt worry about it. Release something that works and then refactor.

Bombinator
10-23-2007, 05:56 PM
I can't tell from your post exactly what you are trying to accomplish but you'll either need one of the factory patterns as mentioned above or depending on how your code is currently structured the visitor pattern may be a better solution for you.