I'm going to have a lot of integer values, and at any value change I might need to update any number of UI elements, other values which are computed from the first ones, etc. Sounds like time for the Visitor pattern, but I'm new to Java (more comfortable in C++). I have:
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
public abstract class Value {
static public interface Listener {
public abstract void valueChanged(Value val);
};
public Value(int init_val) {
mVal = init_val;
mListeners = new ArrayList<WeakReference<Listener>>();
}
public int getValue() { return mVal; }
public void setValue(int val) {
mVal = val;
Iterator<WeakReference<Listener>> iter = mListeners.iterator();
while (iter.hasNext()) {
Listener listen = iter.next().get();
if (listen == null)
iter.remove();
else
listen.valueChanged(this);
}
}
public void addListener(Listener listen) {
cleanListeners();
mListeners.add(new WeakReference<Listener>(listen));
}
private void cleanListeners() {
Iterator<WeakReference<Listener>> iter = mListeners.iterator();
while (iter.hasNext()) {
if (iter.next().get() == null)
iter.remove();
}
}
private int mVal;
private ArrayList<WeakReference<Listener>> mListeners;
};
I'm wondering if there are technical, style, or common practice issues, specifically relating to:
- Is this a good and correct way to use
WeakReference
s, or is there a simpler way? I don't want theValue
to prevent its listeners from getting cleaned up, or to manually break links when a listener is no longer needed by the UI/calculations/whatever. - Use the interface
List<...>
or the actual implementation typeArrayList<...>
when declaring the membermListeners
? - Initialize
mListeners
with an empty list at the member declaration, or in the constructor?
Other comments and suggestions are welcome too.