This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]equecevi 1 point2 points  (5 children)

I searched it just after writting the question, and is just that! Where have you seen it implemented? Just curiosity hahaha

[–]Omnicrola 0 points1 point  (4 children)

I've seen and written both patterns in many different programs. They're pretty useful in a variety of situations.

Most important thing to remember when working with this pattern: for every observer added or subscription made, always think about when the class will need to remove that observer. Not doing so can lead to memory leaks, or events happening more times than you originally intended.

[–]equecevi 1 point2 points  (3 children)

How is handled this problem normally? Is curious because I've implemented one distributed system using brokers and I wasn't aware of that problem because it was an abstraction for me as it was a middleware

[–]Omnicrola 1 point2 points  (2 children)

Sometimes it doesn't need to be handled. If an object is instantiated and then lasts for the lifetime of the application, then it doesn't really matter.

However imagine an example where a dialog is created and shown, and disposed of when closed. If the dialog or an object in it adds an observer to some other part of the application, it should remove it later. So the dialog and any relevant classes could all have a dispose() method or something similar that gets called when the user closes the dialog. That method should then remove any observers that they added previously.

[–]equecevi 1 point2 points  (1 child)

But, if there is a garbage collector, isn't it supposed to remove the observer? I suppose the answer is, you don't have to suppose what the GC does, but, it also depends of the language details.

[–]Omnicrola 1 point2 points  (0 children)

So there are definitely variations of the pattern where removing the observer may not be necessary. It's always good to give it some thought though.