Currently I have faced the following problem: we use some third-party libs in our project and there is a model which supports adding and removing (not getting!) certain type of listeners. And the problem is to add the listener then to remove it somewhere else, where we don’t have its instance. One of the solutions was: to make it singleton so you can add it and remove the same instance (but this is ugly, imho). The second one was the following:
class MyListener implements CoolThirdPartyModelListener{
...
@Override
public boolean equals(Object obj){
if (obj == null){
return false;
}
if(obj == this){
return true;
}
return obj instanceof MyListener;
}
}
And remove it from the listeners list just by calling:
coolThirdPartyModelInstance.removeListener(new MyListener());
But the second one has the ugly equals() method:( And I have been told that its kind tricky to remove listeners that way.
So I want to ask about your opinion about these two variants and maybe (that would be fantastic) you could suggest something more cool then I have found.
Instead of using singleton listener, you can introduce some sort of singleton manager, something like this:
(or you can make a class with bunch of static methods)
Internally implementation can have something like
which would store instances of listeners, which were added for certain model.
Then in
removeListenerFromModel()you can just get listener, that was added for that model from the Map and remove it.