本文从jdk内置的观察者模式来介绍观察者模式。
业务场景:当老师进门的时候,班长带头叫“老师好”,然后全班同学一起交“老师好”
因为太简单,直接上代码
班长继承自Observable
package Observer;
import java.util.Observable;
import java.util.Observer;
public class Monitor extends Observable{
public Monitor() {
super();
}
@Override
public synchronized void addObserver(Observer o) {
super.addObserver(o);
}
@Override
public synchronized void deleteObserver(Observer o) {
super.deleteObserver(o);
}
@Override
public void notifyObservers() {
super.notifyObservers();
}
@Override
public void notifyObservers(Object arg) {
super.notifyObservers(arg);
}
@Override
public synchronized void deleteObservers() {
super.deleteObservers();
}
@Override
protected synchronized void setChanged() {
super.setChanged();
}
@Override
protected synchronized void clearChanged() {
super.clearChanged();
}
@Override
public synchronized boolean hasChanged() {
return super.hasChanged();
}
@Override
public synchronized int countObservers() {
return super.countObservers();
}
}
学生继承自Observer
package Observer;
import java.util.Observable;
import java.util.Observer;
/**
* 观察者
*/
public class Student implements Observer{
String name;
public Student() {
}
public Student(String name) {
this.name = name;
}
@Override
public void update(Observable o, Object arg) {
System.out.println("学生" + this.name + "说老师好");
}
}
测试类:
package Observer;
public class Maintest {
public static void main(String[] args) {
Monitor monitor = new Monitor();
Student student1 = new Student("小明");
monitor.addObserver(student1);
Student student2 = new Student("小蓝");
monitor.addObserver(student2);
Student student3 = new Student("小白");
monitor.addObserver(student3);
// 只有设置了这个值才进行通知
monitor.setChanged();
// 班长通知所有学生老师来了,起立
monitor.notifyObservers();
}
}
结果:
学生小白说老师好
学生小蓝说老师好
学生小明说老师好