Java中观察者模式中主要是Observerable类(被观察者),和Observer接口(观察者)。下面是个简单的demo
//被观察者
package demo;
import java.util.Observable;
public class MyObserverable extends Observable{
//被观察者调用了这个方法,观察者就会发现
@Override
protected synchronized void setChanged() {
// TODO Auto-generated method stub
super.setChanged();
}
//被观察者调用了这个方法,就会向观察者发送改变的信息
@Override
public void notifyObservers(Object arg) {
// TODO Auto-generated method stub
super.notifyObservers(arg);
}
}
//观察者
package demo;
import java.util.Observable;
import java.util.Observer;
public class MyObserver implements Observer{
private String name;
public MyObserver(String name) {
this.name=name;
}
//一旦被观察者有改变,就会调用update方法
@Override
public void update(Observable o, Object arg) {
System.out.println(name+"观察到 "+arg.toString());
}
}
//main方法
package demo;
public class Main {
public static void main(String[] args) {
MyObserver myObserver_1=new MyObserver("observer_1");
MyObserver myObserver_2=new MyObserver("observer_2");
MyObserverable myObserverable=new MyObserverable();
//添加2个观察者
myObserverable.addObserver(myObserver_1);
myObserverable.addObserver(myObserver_2);
String msg="msg has changed";
//设置消息改变点
myObserverable.setChanged();
//通知观察者改变的消息
myObserverable.notifyObservers(msg);
}
}
结果