I'd like to implement the MVC pattern in a difficult situation. The difficulty is that my Models (the entities generating the events) are long-lived, while the Views (the receivers of the events) are short-lived. My problem is that through the connection between the two, the long-lived Models keep my short lived Views alive, i.e. they cannot be garbage-collected.
[MODEL] ------- <weak> -------> [VIEW]
|
<strong>
|
v
[CONTROLLER]
A way to work around this is to store the connections in the Model in a WeakHashMap<View, Controller>. This essentially lets the View to be garbage collected, and when that happens, the WeakHashMap will throw the corresponding Controller out, too. That is, if the Controller doesn't hold a (strong) reference to the View -- which it usually does. In this case the Views are kept alive through the strong references until the Model goes out of scope.
[MODEL] ------- <weak> -------> [VIEW]
| ^
<strong> |
| |
v |
[CONTROLLER] ----------- <strong> ---/
Is there another way to attach listeners to my models that won't keep my views (and controllers) alive?
UPDATE: To answer mdma's question: the Controller keeps a reference to the View, because it needs to update the View. This reference can be weak, but I would like to have the Controllers to be anonymous inner-classes of the View class, in which case the Controller instance has an implicit strong reference to the View instance.