Search code examples
javadesign-patternsclass-design

How to remove registered/added Listeners?


Typically interfaces that let you add listeners also include a remove method something like the following.

interface SomeInterface {
  addListener( Listener) 
  removeListener( Listener );
}

This however suck for several reasons.

  • It is possible to pass a Listener that has not yet been removed to SomeInterface.removeListener().
  • It is also possible to call SI.removeListener() when no Listeners haven registered. One should not be able to call remove before even doing an add.
  • It also means one has to keep a handle of both the Listener and the SI reference in order to remove at some later stage.

I have a proposal which I believe works solves the those three problems, however I want to hear from others to learn from their ideas and proposals which might be more elegant than my own solution.


Solution

  • My proposal would be to have the AddListener method return an object of type ISubscriptionCanceller with one method: CancelSubscription and possibly a SubscriptionActive property. This object would contain all information necessary to cancel a given subscription, whether subscriptions are stored in an array, linked list, or some new data structure yet to be invented. It would naturally be impossible to attempt to cancel a subscription that had not yet been requested, since one would not have the necessary ISubscriptionCanceller to do so.