I believe the simplest solution of them all has been missed a bit...
You would not need more than this in 95% of the cases:
public class Aminal extends Observable {
public void doSomethingThatNotifiesObservers() {
setChanged();
notifyObservers(new Integer(42));
}
}
I'm guessing you'll have no auto boxing, so I made an Integer
object, but part from that, the Observable
class is from JDK1.0 so it should be present in your version of Java.
With autoboxing (in Java 1.5 and later) the notifyObservers
call would look like this:
notifyObservers(42);
In order to catch the sent event you need to implement the Observer
interface:
public class GetInt implements Observer {
@Override
public void update(Observable o, Object arg) {
if (arg instanceof Integer) {
Integer integer = (Integer)arg;
// do something with integer
}
}
}
Then you'll add GetInt
to the Animal
class:
Animal animal = new Animal();
GetInt getint = new GetInt();
animal.addObserver(getint);
This is all standard Java and the Observable
class implements all the observer handling you need.
If you need to be able to trigger Observable
from outside, go with Steve McLeod's solution, but in my experience you'll want to let your class handle what it knows and let other classes interact with it via the Observer
interfaces.
The only thing you need to be aware of is that you need to call setChanged()
before notifyObservers()
or Observable
won't send any events.
I think this is so you can call several setChanged()
and then notify the observers only once, letting them know the class has changed and leaving it up to them to figure out how.
It is also good form to remove the observer once the class where it was created is no longer needed, this to prevent the observer from being left in the observable. Just garbage collecting the observer class will not remove it from the observable.
If you want to observe the class on a per property basis I'd recommend going with PropertyChangeSupport
as described by Adamski above. There's also a VetoableChangeSupport
that you can use if you want listeners to be able to block a change.