1. 什么是觀察者模式?
觀察者模式锭弊,又稱為【發(fā)布-訂閱模式】,可以理解為報(bào)刊社發(fā)布新刊擂错,訂閱者獲取新期刊味滞,訂閱者就相當(dāng)于是觀察者,而且可以有很多觀察者钮呀,報(bào)刊社就是被觀察的對(duì)象剑鞍。
用現(xiàn)實(shí)中的例子比喻一下,學(xué)校里面有一個(gè)小報(bào)刊亭(被觀察者)爽醋,有些學(xué)生(觀察者)在報(bào)刊亭訂閱報(bào)刊攒暇。那具體怎么訂閱呢?就是你交了錢子房,然后留下姓名和手機(jī)號(hào)給老板(注冊(cè)過程)。當(dāng)期刊有更新就轧,報(bào)刊亭老板就給你打電話证杭,告訴你期刊更新了,
然后你就可以去取報(bào)刊(通知過程)妒御。當(dāng)然解愤,看了大概半年后你不想再訂閱,那么你告訴老板說不再訂閱了乎莉,也就是不再續(xù)費(fèi)了送讲。老板會(huì)將你的姓名和電話從他的小本本中刪除了奸笤,即以后不再通知你報(bào)刊更新的信息了(取消注冊(cè)過程)。
這就是觀察者模式的一個(gè)小例子哼鬓,應(yīng)該很好理解吧监右!
2. 觀察者模式練習(xí)例子
(1)舉《Head First設(shè)計(jì)模式》中的例子,天氣情況更細(xì)异希。不過這里我做了更改健盒,改為天氣更新,學(xué)生和工人接收天氣信息變化称簿。
氣象站--->被觀察者扣癣,學(xué)生--->觀察者,工人--->觀察者憨降,天氣若更新父虑,學(xué)生和工人就能獲取到最新的氣象信息,觀察者模式的好處就是授药,不管有多少觀察者只要注冊(cè)后士嚎,就可以獲取被觀察者對(duì)象的信息,即被觀察者的代碼可以不用跟著變化做修改了烁焙。
(2)兩個(gè)接口類設(shè)計(jì)
仿照源碼中的模式航邢,也設(shè)計(jì)Observer接口和Subject接口,然后由具體的類去實(shí)現(xiàn)骄蝇。
下面看一下類圖關(guān)系
Observer接口膳殷,只有一個(gè)天氣更新的接口函數(shù)
public interface Observer {
public void update(Subject subject,Object o);
}
Subject接口,設(shè)計(jì)注冊(cè)九火,移除赚窃,通知觀察者三個(gè)函數(shù)。
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers(Object args);
}
(3)設(shè)計(jì)實(shí)現(xiàn)子類岔激,其中WeatherSender實(shí)現(xiàn)Subject借口哦勒极,Student和Worker實(shí)現(xiàn)Observer接口
WeatherSender類
public class WeatherSender implements Subject{
private Weather weather;
private List<Observer> observers;
private static WeatherSender weatherSender;
private boolean isChanged;
private WeatherSender(){
if(this.observers == null){
this.observers = new ArrayList<>();
}
}
public static WeatherSender getWeatherSender(){
if(weatherSender == null){
return new WeatherSender();
}
else return weatherSender;
}
public void registerObserver(Observer o) {
this.observers.add(o);
}
public void removeObserver(Observer o) {
if(observers.contains(o)){
this.observers.remove(o);
}
}
private void setChanged(){
isChanged = true;
}
/**
* 采用“push”方式通知觀察者(主動(dòng)式)
* @param obj
*/
public void notifyObservers(Object obj) {
if(isChanged){
for(Observer observer : observers){
observer.update(this, obj);
}
}
}
/**
* 采用“pull”方式通知觀察者(被動(dòng)式)
*/
public void notifyObservers(){
notifyObservers(null);
}
/**
* "pull"方式下供觀察者調(diào)用獲取天氣
* @return
*/
public Weather getWeather(){
return this.weather;
}
public void setWeather(Weather weather){
this.weather = weather;
}
/**
* 供外面調(diào)用的接口
* @param weather
*/
public void setWeatherChanged(Weather weather){
setChanged();
notifyObservers(weather);//push方式
/*
setWeather(weather);
notifyObservers();//pull方式
*/
}
}
注意:在notifyObserver()方法設(shè)計(jì)上,在head First設(shè)計(jì)模式中提到了兩種方式虑鼎,push和pull方式辱匿。這里我把它們稱為主動(dòng)式(push)和被動(dòng)式(pull)
- 主動(dòng)式(push):由Subject將weather通過notifyObservers(Object obj)方法傳遞給Observer,即將weather推給Observer
- 被動(dòng)式(pull):Subject不傳遞weather變量炫彩,而是Observer通過獲取WeatherSender匾七,通過它提供的方法自己獲取天氣信息,即由Observer自己將weather拉過來
Student類
public class Student implements Observer{
private Weather weather;
private Subject subject;
public Student(Subject subject){
this.subject = subject;
subject.registerObserver(this);
}
public Weather getWeather() {
return weather;
}
@Override
public void update(Subject subject, Object o) {
//push方式
if(o instanceof Weather){
this.weather = (Weather)o;
}
/*
//pull方式
if(subject instanceof WeatherSender){
this.weather = ((WeatherSender) subject).getWeather();
}
*/
}
public void displayWeather(){
System.out.println("我是Student江兢,當(dāng)前天氣情況:溫度 "
+ weather.getTemperature()+ " 壓力 " + weather.getPressure());
}
}
Worker 類
public class Worker implements Observer{
private Weather weather;
private Subject subject;
public Worker(Subject subject){
this.subject = subject;
subject.registerObserver(this);
}
public Weather getWeather() {
return weather;
}
@Override
public void update(Subject subject, Object o) {
if(o instanceof Weather){
this.weather = (Weather)o;
}
}
public void displayWeather(){
System.out.println("我是Worker昨忆,當(dāng)前天氣情況:溫度 "
+ weather.getTemperature()+ " 壓力 " + weather.getPressure());
}
}
(4)剩下就是一個(gè)Weather類和測試類
WeatherSender類
public class Weather {
private String temperature;
private String pressure;
public String getTemperature() {
return temperature;
}
public Weather(String temperature,String pressure){
this.temperature = temperature;
this.pressure = pressure;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public String getPressure() {
return pressure;
}
public void setPressure(String pressure) {
this.pressure = pressure;
}
}
測試類Test
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
//創(chuàng)建被觀察者
WeatherSender weatherSender = WeatherSender.getWeatherSender();
//創(chuàng)建觀察者,并注冊(cè)
Student student = new Student(weatherSender);
Worker worker = new Worker(weatherSender);
//第一天
Weather weatherFirstDay = new Weather("23℃","1.01*10^5 Pa");
weatherSender.setWeatherChanged(weatherFirstDay);
System.out.println("第一天 天氣情況");
student.displayWeather();
System.out.println("------------------");
worker.displayWeather();
System.out.println("------------------");
//第二天
Weather weatherSecondDay = new Weather("24℃","1.02*10^5 Pa");
weatherSender.setWeatherChanged(weatherSecondDay);
System.out.println("第二天 天氣情況");
student.displayWeather();
System.out.println("------------------");
worker.displayWeather();
System.out.println("------------------");
//第三天
Weather weatherThirdDay = new Weather("25℃","1.03*10^5 Pa");
weatherSender.setWeatherChanged(weatherThirdDay);
System.out.println("第三天 天氣情況");
student.displayWeather();
System.out.println("------------------");
worker.displayWeather();
System.out.println("------------------");
}
}
3.源碼分析
源碼Observer接口,這個(gè)和上面自己寫的例子是一樣的
/**
* A class can implement the <code>Observer</code> interface when it
* wants to be informed of changes in observable objects.
*當(dāng)一個(gè)類在它所觀察的對(duì)象變化時(shí)能夠得到通知,它需要實(shí)現(xiàn)Observer接口
*/
public interface Observer {
void update(Observable o, Object arg);
}
源碼Observable抽象類杉允,源碼中并沒有將Observable設(shè)計(jì)成接口邑贴,個(gè)人認(rèn)為主要是里面公用的方法不要由子類去實(shí)現(xiàn)席里,減少代碼重復(fù)吧!
下面把源碼粘貼過來拢驾,看一下奖磁。
/**
* This class represents an observable object, or "data"
* in the model-view paradigm. It can be subclassed to represent an
* object that the application wants to have observed.
這個(gè)類是被觀察的對(duì)象,或者說是MV模型中的數(shù)據(jù)独旷。它可以被子類化署穗,作為程序中需要觀察的對(duì)象
* <p>
* An observable object can have one or more observers. An observer
* may be any object that implements interface <tt>Observer</tt>. After an
* observable instance changes, an application calling the
* <code>Observable</code>'s <code>notifyObservers</code> method
* causes all of its observers to be notified of the change by a call
* to their <code>update</code> method.
* 被觀察的對(duì)象有一個(gè)或者多個(gè)觀察者。觀察者可能需要實(shí)現(xiàn)Observer接口嵌洼,當(dāng)被觀察對(duì)象實(shí)例發(fā)生變化時(shí)
* 案疲,程序會(huì)調(diào)用Observable的notifyObservers方法,并通過回調(diào)觀察者的update方法麻养,來通知觀察者
* <p>
* The order in which notifications will be delivered is unspecified.
* The default implementation provided in the Observable class will
* notify Observers in the order in which they registered interest, but
* subclasses may change this order, use no guaranteed order, deliver
* notifications on separate threads, or may guarantee that their
* subclass follows this order, as they choose.
* 通知發(fā)送的順序是不固定的褐啡。Observable 類中所提供的默認(rèn)實(shí)現(xiàn)將按照其注冊(cè)的順序來通知觀察者,
* 但是子類可能改變此順序鳖昌,從而使用非固定順序在單獨(dú)的線程上發(fā)送通知备畦,
* 或者也可能保證其子類遵從其所選擇的順序。
* <p>
* Note that this notification mechanism has nothing to do with threads
* and is completely separate from the <tt>wait</tt> and <tt>notify</tt>
* mechanism of class <tt>Object</tt>.
* 注意這個(gè)通知機(jī)制和線程無關(guān)许昨,并且要和Object的等待喚醒機(jī)制區(qū)分開
* <p>
* When an observable object is newly created, its set of observers is
* empty. Two observers are considered the same if and only if the
* <tt>equals</tt> method returns true for them.
*當(dāng)一個(gè)被觀察對(duì)象創(chuàng)建后懂盐,它的觀察者集合時(shí)空的。
*兩個(gè)觀察者當(dāng)且僅當(dāng)equals方法返回true時(shí)認(rèn)為他們是同一個(gè)觀察者
*/
public class Observable {
private boolean changed = false;
private Vector<Observer> obs;//源碼中使用Vector糕档,保證線程安全
/** Construct an Observable with zero Observers. */
public Observable() {
obs = new Vector<>();
}
/**
* Adds an observer to the set of observers for this object, provided
* that it is not the same as some observer already in the set.
* The order in which notifications will be delivered to multiple
* observers is not specified. See the class comment.
*
* @param o an observer to be added.
* @throws NullPointerException if the parameter o is null.
*/
public synchronized void addObserver(Observer o) {
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
}
/**
* Deletes an observer from the set of observers of this object.
* Passing <CODE>null</CODE> to this method will have no effect.
* @param o the observer to be deleted.
*/
public synchronized void deleteObserver(Observer o) {
obs.removeElement(o);
}
//這個(gè)方法就是采用“pull”的方法
public void notifyObservers() {
notifyObservers(null);
}
//這個(gè)方法是采用“push”的方法
public void notifyObservers(Object arg) {
/*
* a temporary array buffer, used as a snapshot of the state of
* current Observers.
*/
Object[] arrLocal;
synchronized (this) {
/* We don't want the Observer doing callbacks into
* arbitrary code while holding its own Monitor.
* The code where we extract each Observable from
* the Vector and store the state of the Observer
* needs synchronization, but notifying observers
* does not (should not). The worst result of any
* potential race-condition here is that:
* 1) a newly-added Observer will miss a
* notification in progress
* 2) a recently unregistered Observer will be
* wrongly notified when it doesn't care
* 從被觀察對(duì)象的Vector中取出的code莉恼,包含觀察者的狀態(tài),需要線程同步速那,但是在
* 通知觀察者時(shí)俐银,不需要同步。潛在的資源爭奪下端仰,最糟糕的情況:
* (1)一個(gè)新加入的觀察者將會(huì)錯(cuò)過正在進(jìn)行消息通知
* (2)一個(gè)剛剛?cè)∠?cè)的觀察者將會(huì)“很無奈的”接收他不想接受的消息
*/
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}
/**
* Clears the observer list so that this object no longer has any observers.
*/
public synchronized void deleteObservers() {
obs.removeAllElements();
}
/**
* Marks this <tt>Observable</tt> object as having been changed; the
* <tt>hasChanged</tt> method will now return <tt>true</tt>.
*/
protected synchronized void setChanged() {
changed = true;
}
/**
* Indicates that this object has no longer changed, or that it has
* already notified all of its observers of its most recent change,
* so that the <tt>hasChanged</tt> method will now return <tt>false</tt>.
* This method is called automatically by the
* <code>notifyObservers</code> methods.
*
* @see java.util.Observable#notifyObservers()
* @see java.util.Observable#notifyObservers(java.lang.Object)
*/
protected synchronized void clearChanged() {
changed = false;
}
/**
* Tests if this object has changed.
*
* @return <code>true</code> if and only if the <code>setChanged</code>
* method has been called more recently than the
* <code>clearChanged</code> method on this object;
* <code>false</code> otherwise.
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#setChanged()
*/
public synchronized boolean hasChanged() {
return changed;
}
/**
* Returns the number of observers of this <tt>Observable</tt> object.
*
* @return the number of observers of this object.
*/
public synchronized int countObservers() {
return obs.size();
}
}
4. 總結(jié)
源碼和上面自己寫的例子中的基本思路是一致捶惜,源碼中設(shè)計(jì)的更加全面,加入了線程安全荔烧。
觀察者模式在java源碼和android源碼中都有很多應(yīng)用吱七,如在android中的監(jiān)聽器,控件設(shè)置點(diǎn)擊事件鹤竭,注冊(cè)監(jiān)聽器踊餐,就是觀察者模式。所以理解設(shè)計(jì)模式對(duì)于讀源碼有很大幫助诺擅!
參考 《Head First設(shè)計(jì)模式》