views:

41

answers:

1

I'm trying to do a small and simple GUI in C++ (with SDL). I'm experimenting with the Composite pattern to have a flexible solution.

I've got a Widget class, with Component objects : for instance, there is a PaintingComponent ; if I want to draw a box, I'll use a PaintingBoxComponent, that inherits from the PaintingComponent.

The ideal Widget class would look a bit like that :

Class Widget
{
  private:
  vector<Component*> myComponents;

  public:
  // A small number of methods able to communicate with the component 
  // without knowing their types
}

My question is simple : what is the best way to activate this component when I need it ?

I first went with a "display" function in the Widget class. But I see two problems :

1°) I'm losing the pure polymorphism of "Compoonent" in Widget, since I'm forced to declare a particular component of the widget as PaintingComponent. I can deal with this, since it's logical that a Widget should be displayed.

2°) More troublesome, I need to pass information between my main programm and my PaintingComponent. Either I pass the SDL_Surface* screen to the PaintingComponent, and it paints the image it drew on it, or I give to my component a reference to the object that need to receive the image it has drawn (and this object will paint the image on the screen). In both cases, Widget will have to handle the data, and will have to know what a SDL_Surface* is. I'm loosing the loose coupling, and I don't want that.

Then, I considered using a "Visitor" pattern, but I'm not used to it and before I try to implement it, I'd like to have your advice.

How would you proceed to have a flexible and solid solution in this case ? Thanks in advance !

+1  A: 

If you plan to change graphic system later, you could implement this pattern. Visitor goes to root node, then recursively to all children, drawing them on some surface (known only to Visitor itself). You can gather "display list" with that, then optimize it before drawing (for example, on OpenGL apply z-sorting (lower z first).

alxx
Thank you, I've managed to do it approximately as you describe it. But it changes so many things in the global architecture it's a bit puzzling at first. Now, I have to figure how to uses visitor + widget + Widget inside widgets ! Anyway, you convinced me : better to be able to change graphics later. Thanks again.
Raveline