4

I've been reading about how to implement proper MVC in a C++ application and basically came to the point that there are 2 ways of implementing this :

  • observer pattern
  • signal/slot

However, in both cases, the exemples I read all follow a structure in which the subject can change and notify it's observer(s), but the observer never changes the subject. Now this cases arises a few "problems".

Let's say I have a class called Text (a model component), another classed called TextEditor (a GUI component) which someway displays 'Text' AND should be able to modify it and a few other classes which can modify the 'Text' as well .

Right, so I use observer pattern, make 'Text' the subject and 'TextEditor' the observer. No big deal.

If 'Text' is changed in some way, Text calls Text::notify() and my TextEditor will reflect the change. Fine.

Now, what if I use the TextEditor to modify the Text ?

'TextEditor' knows about 'Text', so it calls something like textInstance.setText(...) ...and at the end of setText, 'Text' calls notify, and 'TextEditor' is notified of a change it made itself ! 'Text' cannot even send a notification to everybody except 'TextEditor' because it's not suppose to know about it's observers !

I've got the feeling that this is not right, not "clean" even performance-reasons asside . I'd bet there's a better way to implement this but I'm stuck. Anybody has hints ?

I'm not realy looking to a pre-made C++ implementation, but more to an understanding of how I should see things correctly.

Dinaiz
  • 2,213
  • 4
  • 22
  • 32

1 Answers1

4

The pattern is clean. You are making the assumption than TextEditor now what setText is doing and so don't need to be notified. What if the Text has been frozen and refuse to modify itself. Text can also be a kind of logger which append any new text and add timestamp etc.

So, it's perfectly clean for TextEditor to "ask" Text to do something and then check what the result is. So TextEditor is not notified for a change it made itself but for how the change it asked for has been managed.

If you really have performance issue what you can do hack the observer pattern in different way

  • remove TextEditor as an observer before calling sendText and readding it afterward
  • if all the call are synchronous : preventing TextEditor of auto-refresh by setting a attribute
  • etc ...
mb14
  • 22,276
  • 7
  • 60
  • 102