组成部分:
观测者:Observer,也称它为订阅者,即Subscriber
被观测者:Observable,即可以被观察的东西,有时候会称之为主题,即Subject
情景:
天气预报订阅
如果天气发生变化,通知订阅者,订阅事物与订阅者可能是单对单也可能是一对多 多对多的关系。
创建天气model:
public class Weather {
private String description;
public String getDescription() {
return description;
}
public Weather(String description) {
this.description = description;
}
@Override
public String toString() {
return "Weather{" +
"description='" + description + '\'' + '}';
}
}
创建被观测者,即observable:
其应该至少提供:订阅、退订、状态发生变化通知观测者的方法
public class Observable<T> {
/**
* 订阅者们
*/
ArrayList<Observer<T>> observers = new ArrayList<>();
/**
* 订阅
* @param observer
*/
public void register(Observer<T> observer){
if (observer==null) return;
synchronized (this){
if (observers.contains(observer))return;
observers.add(observer);
}
}
/**
* 退订
* @param observer
*/
public void unregister(Observer<T> observer){
observers.remove(observer);
}
/**
* 通知各个订阅者
*/
public void notifyObserver(T data){
for (Observer<T> observer :observers){
observer.onUpdate(data);
}
}
}
创建观测者接口,观测者只需接收状态变化:
public interface Observer<T> {
void onUpdate(T data);
}
test:
public class Test {
public static void main(String[] s){
Observable<Weather> observable = new Observable<>();
Observer<Weather> xiaoming = new Observer<Weather>() {
@Override
public void onUpdate(Weather data) {
System.out.println("小明接收到的订阅:"+data.getDescription());
}
};
Observer<Weather> xiaohong = new Observer<Weather>() {
@Override
public void onUpdate(Weather data) {
System.out.println("小红接收到的订阅:"+data.getDescription());
}
};
observable.register(xiaoming);
observable.register(xiaohong);
Weather weather = new Weather("多云");
observable.notifyObserver(weather);
weather = new Weather("阴天");
observable.notifyObserver(weather);
weather = new Weather("晴天");
observable.notifyObserver(weather);
}
}