Observer Pattern in J2ME
I know that Observer pattern is not supported in the J2ME as开发者_如何学运维 Observer and Observable are not in the J2ME.
So, is there any work around to using Observer pattern in J2ME? I want to make a Thread making some logic and when it finish its work notify the main thread to update the UI.The observer/observable pattern does not require specific classes from the Java library. All those classes do is implement some parts of the observer pattern for you. You can make your own classes observable by managing observers yourself. Note that the following doesn't explain how to make one thread wait for another -- that's a different problem.
You can write a listener interface like this:
public interface FooListener {
void fooChanged(int newValue);
}
You can manage a set of listeners in a class like this:
public class Foo {
private int value = 0;
private final Collection<FooListener> listeners = new ArrayList<FooListener>();
public void addFooListener(FooListener listener) {
listeners.add(listener);
}
public void removeFooListener(FooListener listener) {
listeners.remove(listener);
}
public void change(int newValue) {
value = newValue();
for (FooListener l : listeners) {
l.fooChanged(newValue);
}
}
public int getValue() {
return value;
}
}
Here's a simple example of a listener implementation.
public class PrintingFooListener implements FooListener {
public void fooChanged(int newValue) {
System.out.println("New Foo value: " + newValue);
}
}
The following program would print New Foo value: 10
.
public static void main(String[] args) {
PrintingFooListener myListener = new PrintingFooListener();
Foo myFoo = new Foo();
foo.addFooListener(myListener);
foo.change(10);
}
精彩评论