Created
September 19, 2012 20:41
-
-
Save dougkeen/3752131 to your computer and use it in GitHub Desktop.
Generic observable pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.dougkeen.util; | |
import java.util.WeakHashMap; | |
import org.apache.commons.lang3.ObjectUtils; | |
public class Observable<T> { | |
private T value; | |
private WeakHashMap<Observer<T>, Boolean> listeners = new WeakHashMap<Observer<T>, Boolean>(); | |
public Observable() { | |
super(); | |
} | |
public Observable(T value) { | |
super(); | |
this.value = value; | |
} | |
public T getValue() { | |
return value; | |
} | |
public void setValue(T value) { | |
if (!ObjectUtils.equals(this.value, value)) { | |
this.value = value; | |
notifyOfChange(value); | |
} | |
} | |
public void registerObserver(Observer<T> observer) { | |
listeners.put(observer, true); | |
} | |
public void unregisterObserver(Observer<T> observer) { | |
listeners.remove(observer); | |
} | |
protected void notifyOfChange(T value) { | |
for (Observer<T> listener : listeners.keySet()) { | |
if (listener != null) { | |
listener.onUpdate(value); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.dougkeen.util; | |
public interface Observer<T> { | |
void onUpdate(final T newValue); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment