JDK提供了观察者模式的实现类java.util.Observer,java.util.Observable.
java.util.Observer为观察者。
java.util.Observable观察物。
1.观察物
2.观察者
3.测试类
java.util.Observer为观察者。
java.util.Observable观察物。
1.观察物
package observer;
import java.util.Observable;
public class Publisher extends Observable {
private String magazineName;
public String getMagazineName() {
return magazineName;
}
public void publish(String magazineName) {
this.magazineName = magazineName;
setChanged();// set the changed signal
notifyObservers();// notify all the observers
}
}
2.观察者
package observer;
import java.util.Observable;
import java.util.Observer;
public class Reader implements Observer {
// when the observable changed ,
// it will notify all the observers and this method will be invoke
@Override
public void update(Observable o, Object arg) {
if(o instanceof Publisher){
Publisher p = (Publisher) o;
System.out.println("i want to read magazine. " + p.getMagazineName());
}
}
}
3.测试类
package observer;
public class Main {
public static void main(String[] args) {
// create observer
Reader reader=new Reader();
// create observable
Publisher publisher = new Publisher();
// add observer
publisher.addObserver(reader);
// observable do some action
publisher.publish("I am antlove.");
}
}