Pros and Cons of Listeners as WeakReferences

前端 未结 12 1035
天命终不由人
天命终不由人 2020-12-04 12:18

What are the pros and cons of keeping listeners as WeakReferences.

The big \'Pro\' of course is that:

Adding a listener as a WeakReference means the listener

12条回答
  •  时光说笑
    2020-12-04 12:20

    I have seen tons of code where listeners were not unregistered properly. This means they were still called unnecessarily to perform unnecessary tasks.

    If only one class is relying on a listener, then it is easy to clean, but what happens when 25 classes rely on it? It becomes much trickier to unregister them properly. The fact is, your code can start with one object referencing your listener and end up in a future version with 25 objects referencing that same listener.

    Not using WeakReference is equivalent to taking a big risk of consuming unnecessary memory and CPU. It is more complicated, trickier and requires more work with hard references in the complex code.

    WeakReferences are full of pros, because they are cleaned up automatically. The only con is that you must not forget to keep a hard reference elsewhere in your code. Typically, that would in objects relying on this listener.

    I hate code creating anonymous class instances of listeners (as mentioned by Kirk Woll), because once registered, you can't unregister these listeners anymore. You don't have a reference to them. It is really bad coding IMHO.

    You can also null a reference to a listener when you don't need it anymore. You don't need to worry about it anymore.

提交回复
热议问题