Java.util工具包中提供了观察者和被观察者的两个对象
下面是一个例子
public class SimpleObserver implements Observer {
public SimpleObserver(SimpleObservable observable){
observable.addObserver(this);
}
@Override
public void update(Observable arg0, Object arg1) {
// TODO Auto-generated method stub
System.out.println("data is changed :" + ((SimpleObservable)arg0).getData());
}
}
Observer对象提供了update方法,
参数一:该观察者观察的对象,
参数二:Observable中的notifyObservers(Object data)方法提供的传值,使观察者可以知道被观察者的数据的改变
调用时机:被观察者数据的setter方法中
public class SimpleObservable extends Observable{
private int data=0;
public int getData() {
return data;
}
public void setData(int data) {
if(data!=this.data){
this.data = data;
setChanged();//设置发生改变
notifyObservers();//通知观察者,状态发生了改变
}}}
被观察者对象在setter函数中调用setchanged和notifyObservers()对象来进行通知观察者
测试主函数:
public class TestMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
SimpleObservable observable =new SimpleObservable();
SimpleObserver observer1=new SimpleObserver(observable);
observable.setData(1);
observable.setData(2);
observable.setData(2);
observable.setData(3);
}
}
输出结果:
data is changed :1
data is changed :2
data is changed :3