C ++ "bidirectional" observer pattern

I read about how to implement the correct MVC in a C ++ application and basically came to the conclusion that there are two ways to implement this:

  • observer pattern
  • signal / slot

However, in both cases, the examples I read follow a structure in which the subject can change and notify the observer (s), but the observer never changes the subject. Now, in these cases, several "problems" arise.

Let's say I have a class called Text (component of the model), another class called TextEditor (component of the GUI), which somehow displays the "Text" and should be able to modify it, and several other classes that can modify the "Text" 'also.

That's right, so I use the observer pattern, make the “Text” subject and the “TextEditor” observer. Nothing wrong.

If the “Text” is somehow changed, Text calls Text :: notify (), and my TextEditor will reflect this change. Good.

Now, if I use TextEditor to change the text?

"TextEditor" knows about "text", so it calls something like textInstance.setText (...) ... and at the end of setText, "Text" messages are notified, and "TextEditor" is notified of the change it made! “Text” cannot even send a notification to everyone except “TextEditor”, because it should not know about this observers!

I have a feeling that this is wrong, and not "clean", even performance considerations. I would put there the best way to implement this, but I'm stuck. Does anyone have any hints?

I am not very good at ready-made implementation in C ++, but more for understanding how to see things correctly.

+4
source share
1 answer

Sample is clean. You make an assumption than TextEditor, now that setText does, and therefore does not need to be notified. What to do if the text has been frozen and refuses to modify itself. The text can also be a kind of registrar that adds new text and adds a timestamp, etc.

So, it perfectly clears the TextEditor to “ask” the text to do something, and then check what the result is. Thus, the TextEditor is not notified of the change it made, but how the change that it requested was made.

If you really have a performance issue, you can crack the observer pattern differently.

  • remove TextEditor as an observer before calling sendText and then reading it
  • if all calls are synchronous: preventing TextEditor from automatically updating by setting the attribute
  • etc.
+4
source

All Articles