I am working a lot with the observer pattern in my current application. Each object is, on average, observing 3 other objects. And I fear that maybe sometimes I might miss to correctly remove observers that I have previously registered. This might lead to the lapsed observer problem and memory leaks which I would like to avoid.
Unfortunately, there is no compile-time way of detecting this, so I thought about implementing a run-time detection mechanism to throw an exception when a lapsed observer is detected.
But I dont quite now how to do this. I have one idea although it does not sound too solid to me:
I will add a finalize() method to all my observable objects. In this method they will check if there are any observers left observing them. If there are, this will be logged to let me know.
But I dont think this would be able to detect all of them. Are there any other thoughts or suggestions? Any input on this is greatly appreciated.
Thanks in advance.