The ListenersCollection class
I said I implemented this, and I wasn't lying. I supply the code for the
ListenersCollection here, free for your usage - It's attached with an Apache License, so don't lose that!
Here's the code:
/**
* Copyright 2005-2006 Aviad Ben Dov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.crazyredpanda.util.collections;
import java.util.Collection;
import java.util.TreeSet;
import java.util.Map;
import java.util.TreeMap;
public final class ListenersCollection<Listener, EventArgs> {
public interface ListenerInvoker<Listener, EventArgs> {
void invoke(Listener l, EventArgs args);
}
private final ListenerInvoker<Listener, EventArgs> invoker;
private final Collection<Listener> listeners = new TreeSet<Listener>();
private final Map<Listener, Boolean> delayedListeners = new TreeMap<Listener, Boolean>();
private boolean isDelayed = false;
public ListenersCollection(ListenerInvoker<Listener, EventArgs> invoker) {
this.invoker = invoker;
}
public synchronized void addListener(Listener l) {
if (isDelayed) {
delayedListeners.put(l, true);
} else {
listeners.add(l);
}
}
public synchronized void removeListener(Listener l) {
if (isDelayed) {
delayedListeners.put(l, false);
} else {
listeners.remove(l);
}
}
public synchronized void fireEvent(EventArgs args) {
isDelayed = true;
for (Listener l : listeners) {
invoker.invoke(l, args);
}
isDelayed = false;
// handing delayed un/registartions
for (Map.Entry<Listener, Boolean> entry : delayedListeners.entrySet()) {
if (entry.getValue()) {
listeners.add(entry.getKey());
} else {
listeners.remove(entry.getKey());
}
}
delayedListeners.clear();
}
}
Comments (9)