简体   繁体   English

观察者模式 - 删除主题(垃圾收集器何时删除主题)

[英]Observer pattern - delete subject (when is the subject deleted by garbage collector)

I have one class subject implementing multiple "observable" interfaces and I need to delete this subject .我有一个实现多个“可观察”接口的 class主题,我需要删除这个主题 Because in Java you are not deleting the object yourself (the garbage collector does it for you) I need to delete all references to this object (so I need to unsubscribe from all observers ) is it correct to create method delete which will unsubscribe all observers?因为在 Java 中,您没有自己删除 object(垃圾收集器为您完成)我需要删除对此 object 的所有引用(所以我需要取消订阅所有观察者的正确方法删除它会取消订阅所有观察者) ? Or is there some better way (I tried to google it but I didn't found anything)或者有没有更好的方法(我试图用谷歌搜索,但我没有找到任何东西)

In other words could anyone tell me when will be the subject deleted by garbage collector?换句话说,谁能告诉我垃圾收集器何时会删除主题?

It's hard to tell when an object will be deleted by the garbage collector.很难判断垃圾收集器何时会删除 object。 For me it depends on the GC you are using.对我来说,这取决于您使用的 GC。 So if an object has no reference, indeed it becomes eligible for garbage collection but you won't exactly know when it will actually occur.因此,如果 object 没有引用,则它确实有资格进行垃圾收集,但您不会确切知道它何时会真正发生。

Now, to give an answer about your observable pattern, you will need to create a method deleteObservers to remove reference on the subject.现在,要给出有关您的可观察模式的答案,您将需要创建一个方法deleteObservers来删除对该主题的引用。 I don't know how you implemented the pattern, the Java class Observable has this method but this is deprecated since Java 9.我不知道您是如何实现该模式的,Java class Observable具有此方法,但自 Java 9 以来已弃用此方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM