In designing an API that provides an event listening interface, it seems there are two conflicting ways of treating calls to add/remove listeners:
Multiple calls to addListener will only add a single listener (like adding it to a set); can be removed with a single call to removeListener.
Multiple calls to addListener will add a listener each time (like adding it to a list); must be balanced by multiple calls to removeListener.
I've found an example of each: (1) - Will duplicate addEventListener calls create duplicate listener entries? and (2) - jQuery: Does adding an event listener overwrite the previous listener of the same event?. (2) is also used in SWT and Swing event listeners.
In my implementations, I tend to stick with (2) since it provides a cleaner setup/teardown type interface and reveals bugs where 'setup' is unintentionally being done twice, and is consistent with most implementations I've seen.
This leads me to my question - Is there a particular architecture or other underlying design that lends itself better to the other implementation? (ie: why does the other pattern exist?)
addListener(foo); addListener(foo); addListener(bar);. Does your case #1 one add onefooand onebar, or onlybar(i.e.,baroverwritesfooas the listener)? In case #2, wouldfoofire twice, or once? – apsillers Jan 2 at 17:55foo==bar, then it would overwrite, otherwise, it would have onefooand onebaras listeners. If it always overwrote, it wouldn't be a set, but a single object that represented an observer. – Chris Jan 2 at 17:59