Skip to content

Instantly share code, notes, and snippets.

@Ider
Created November 5, 2013 21:27
Show Gist options
  • Save Ider/7326631 to your computer and use it in GitHub Desktop.
Save Ider/7326631 to your computer and use it in GitHub Desktop.
This class represents an generic observer/listener pattern.
package com.iderzheng.util;
import java.util.HashSet;
import java.util.Set;
/**
* This class represents an generic observer object.
*
* @author Ider Zheng
* @since 10/31/13.
*/
public abstract class Observer<L> {
/**
* Use set to make add/remove Listener in constant time.
* If the order of listeners is important, use
*/
Set<L> listeners = new HashSet<L>();
public Observer() {}
/**
* Adds an listener to the set of listeners for this object, provided
* that it is not the same as some listener already in the collection.
*
* @param l an listener to be added.
* @throws NullPointerException if the parameter l is null.
*/
public synchronized void addListener(L l) {
if (l == null)
throw new NullPointerException();
if (!listeners.contains(l)) {
listeners.add(l);
}
}
/**
* Remove a listener from the set of listeners of this observer.
* Passing <CODE>null</CODE> to this method will have no effect.
* @param l the listener to be deleted.
*/
public synchronized void removeListener(L l) {
listeners.remove(l);
}
/**
* Clears the listener list so that this object no longer has any listeners.
*/
public synchronized void removeAllListeners() {
listeners.clear();
}
/**
* Returns the number of listeners of this <tt>Observable</tt> object.
*
* @return the number of listeners of this object.
*/
public synchronized int countListeners() {
return listeners.size();
}
/**
* Each listener is passed to <code>dispatch</code> method for custom
* notification.
* This method is equivalent to:
* <blockquote><tt>
* notifyListeners(null)</tt></blockquote>
*/
public void notifyListeners() {
notifyListeners(null);
}
/**
* Each listener is passed to <code>dispatch</code> method for custom
* notification.
* arguments: this observable object and the <code>arg</code> argument.
*/
public void notifyListeners(Object arg) {
/*
* a temporary array buffer, used as a snapshot of the state of
* current Listeners.
*/
Object[] arrLocal;
synchronized (this) {
arrLocal = listeners.toArray();
}
for (Object o : arrLocal) {
dispatch((L)o, arg);
}
}
/**
* Subclass implement this method to call specific method on listener.
* @param listener
* @param arg
*/
abstract protected void dispatch(L listener, Object arg);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment