1. 程式人生 > >設計模式之觀察者模式之一、引出觀察者mosh

設計模式之觀察者模式之一、引出觀察者mosh

一、氣象站提供的類

package org.observer.pt;

/**
 * 
 * @author mexican 專案描述:該類有氣象站提供氣象的溫度、氣壓、溼度,當資料有變化的時候,直接公佈到訊息版塊,而這個舉動是實時更改的
 */
public class WeatherData {
	// 溫度
	private int wd;
	// 氣壓
	private int qy;
	// 溼度
	private int sd;
	// 資訊公佈
	private CurrentConditions cc;

	// 構造氣象類的時候,將公告欄給初始化
	public WeatherData(CurrentConditions cc) {
		this.cc = cc;
	}

	public void dataChange() {
		// 當氣象局獲取的氣象資料發生改變會呼叫dataChange這個method,然後直接公佈到資訊欄
		cc.update(getWd(), getQy(), getSd());
	}

	// 該方法用於模擬氣象站獲取到資料的時候,將氣象資料設定進去
	public void setData(int wd, int qy, int sd) {
		this.wd = wd;
		this.qy = qy;
		this.sd = sd;
		//這裡表名氣象站有新的資料了,就直接呼叫dataChange
		dataChange();
	}

	public int getWd() {
		return wd;
	}

	public void setWd(int wd) {
		this.wd = wd;
	}

	public int getQy() {
		return qy;
	}

	public void setQy(int qy) {
		this.qy = qy;
	}

	public int getSd() {
		return sd;
	}

	public void setSd(int sd) {
		this.sd = sd;
	}

}
二、第三方對接公司氣象公告板
package org.observer.pt;

/**
 * 
 * @author mexican 公告板
 */
public class CurrentConditions {
	/**
	 * update 方法用於更新資料
	 */
	//溫度
	private int wd;
	//氣壓
	private int qy;
	//溼度
	private int sd;
	/**
	 * 
	 * @param wd 溫度
	 * @param qy 氣壓
	 * @param sd 溼度
	 *  desc:用於接受氣象站也就是WeatherData提供的氣象資料
	 */
	public void update(int wd,int qy,int sd) {
		this.wd=wd;
		this.qy=qy;
		this.sd=sd;
		//當發生改變之後立即現實公佈氣象結果
		display();
	}
	
	/**
	 * 用於現實當前氣象資料結果
	 */
	public void display() {
		//這裡簡單模擬就直接打印出來
		System.out.println("****今日溫度是:"+wd+"****");
		System.out.println("****今日氣壓是:"+qy+"****");
		System.out.println("****今日溼度是:"+sd+"****");
	}
}


三、測試結果
package org.observer.pt;

/**
 * 
 * @author mexican 公告板
 */
public class CurrentConditions {
	/**
	 * update 方法用於更新資料
	 */
	//溫度
	private int wd;
	//氣壓
	private int qy;
	//溼度
	private int sd;
	/**
	 * 
	 * @param wd 溫度
	 * @param qy 氣壓
	 * @param sd 溼度
	 *  desc:用於接受氣象站也就是WeatherData提供的氣象資料
	 */
	public void update(int wd,int qy,int sd) {
		this.wd=wd;
		this.qy=qy;
		this.sd=sd;
		//當發生改變之後立即現實公佈氣象結果
		display();
	}
	
	/**
	 * 用於現實當前氣象資料結果
	 */
	public void display() {
		//這裡簡單模擬就直接打印出來
		System.out.println("****今日溫度是:"+wd+"****");
		System.out.println("****今日氣壓是:"+qy+"****");
		System.out.println("****今日溼度是:"+sd+"****");
	}
}

****今日溫度是:23****
****今日氣壓是:50****
****今日溼度是:100****


總結:首先第三方公司CurrentConditions公佈今日氣象資料這種方式能實現,如果再有例外一個公司需要接入氣象站,用於計算明日的氣象資料,溫度、氣壓,溼度。那麼有的單獨寫一個明日的氣象公告欄,從而在氣象站中的dataChange方法,有的新增明日公告欄的訊息的方法,進而有的重新進行編譯氣象站這個類,氣象站應該作為單獨的執行緒進行執行,從而引出觀測站模式。