观察者模式又被称作发布/订阅模式,观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。
Java库中的观察者和被观察者.png image.pngJDK库代码:
libcore/ojluni/src/main/java/java/util/Observer.java
public interface Observer {
/**
* This method is called whenever the observed object is changed. An
* application calls an <tt>Observable</tt> object's
* <code>notifyObservers</code> method to have all the object's
* observers notified of the change.
*
* @param o the observable object.
* @param arg an argument passed to the <code>notifyObservers</code>
* method.
*/
void update(Observable o, Object arg);
}
libcore/ojluni/src/main/java/java/util/Observable.java
public class Observable {
private final ArrayList<Observer> observers;
public synchronized void addObserver(Observer o){...}
public synchronized void deleteObserver(Observer o){...}
public void notifyObservers() {
notifyObservers(null);
}
public void notifyObservers(Object arg) {
Observer[] arrLocal;
synchronized (this) {
...
arrLocal = observers.toArray(new Observer[observers.size()]);
clearChanged();
}
for (int i = arrLocal.length-1; i>=0; i--)
arrLocal[i].update(this, arg);// 这里逐个调用观察者的update方法
}
简单的代码实现:
public class User implements Observer {
public String name;
public User(String name) {
this.name = name;
}
@Override
public void update(Observable o, Object arg) {
System.out.println("Hi "+name +",公众号更新了内容:"+arg);
}
}
public class Gamedaily extends Observable {
public void postNewArticle(String content){
//内容发生改变
setChanged();
//通知所有订阅者改变的内容
notifyObservers(content);
}
}
public class Client {
public static void main(String[] args) {
Gamedaily gamedaily = new Gamedaily();
User user1 = new User("user1");
User user2 = new User("user2");
User user3 = new User("user3");
//将观察者注册到可观察者的通知列表中。
gamedaily.addObserver(user1);
gamedaily.addObserver(user2);
gamedaily.addObserver(user3);
gamedaily.postNewArticle("新文章来了");
}
}
网友评论