1、广播站
package observer;
import java.util.Observable;
//广播站
public class Radio extends Observable{
private String content;
public void broadcast(String content){
this.content = content;
//有新内容
setChanged();
//广播
notifyObservers();
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
2、收听者
package observer;
import java.util.Observable;
import java.util.Observer;
public class Reader implements Observer{
//持有广播的引用(手里拿着收音机)
Observable radio;
Reader(Observable radio){
this.radio = radio;
radio.addObserver(this);
}
//接收到广播,并且输出内容
@Override
public void update(Observable radio, Object arg1) {
Radio r = (Radio)radio;
System.out.println("get:"+r.getContent());
}
}
3、应用程序
package observer;
public class Main {
public static void main(String[] args) {
//创建一个广播站
Radio r = new Radio();
//创建两个收听者
Reader reader1 = new Reader(r);
Reader reader2 = new Reader(r);
//广播站发通知
r.broadcast("testing...");
}
}
4、输出结果
5、总结
观察者模式