首先有一個更新天氣佈告板的系統。
public class ConditionsPanel{
public void update(float temp, float humidity, float pressure){
Debug.Log ("ConditionsPanel");
Debug.Log ("temp: " + temp);
Debug.Log ("humidity: " + temp);
Debug.Log ("pressure: " + temp);
}
}
public class StatisticsPanel{
public void update(float temp, float humidity, float pressure){
Debug.Log ("StatisticsPanel");
Debug.Log ("temp: " + temp);
Debug.Log ("humidity: " + temp);
Debug.Log ("pressure: " + temp);
}
}
public class ForecastPanel{
public void update(float temp, float humidity, float pressure){
Debug.Log ("ForecastPanel");
Debug.Log ("temp: " + temp);
Debug.Log ("humidity: " + temp);
Debug.Log ("pressure: " + temp);
}
}
public class WeatherData{
public ConditionsPanel conditionsDisplay = new ConditionsPanel();
public StatisticsPanel statisticsDisplay = new StatisticsPanel();
public ForecastPanel forecastPanel = new ForecastPanel();
public float getTemperature(){
return 1.0f;
}
public float getHumidity(){
return 2.0f;
}
public float getPressure(){
return 3.0f;
}
public void mentsChanged(){
float temp = getTemperature ();
float humidity = getHumidity ();
float pressure = getPressure ();
conditionsDisplay.update (temp, humidity, pressure);
statisticsDisplay.update (temp, humidity, pressure);
forecastPanel.update (temp, humidity, pressure);
}
}
注意到氣象站提供getter方法供各種佈告板使用,這裏有3個佈告板。
也就是一對多的關係。
更新佈告板時,是針對具體實現編程,這將導致以後增加或者刪除佈告板時,需要修改或者代碼。
當我們需要增加公告板時,除了要添加新的公告板類外,還需要修改WeatherDate的mentsChanged方法,公告板越來越多時,這段代碼也會越來越冗長,稍有變動便要修改或刪除。(兩者耦合過緊,一方改動牽動着另一方)
公告板接收的參數是一樣的,可以考慮整合。
//主題
public interface Subject{
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObserver();
}
//氣象站
public class WeatherData : Subject{
private ArrayList observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData(){
observers = new ArrayList ();
}
//註冊
public void registerObserver(Observer o){
observers.Add (o);
}
//移除
public void removeObserver(Observer o){
int i = observers.IndexOf (o);
if (i > 0) {
observers.Remove(i);
}
}
//通知
public void notifyObserver(){
foreach (Observer o in observers) {
o.update(temperature, humidity, pressure);
}
}
public void measurementsChanged(){
notifyObserver ();
}
}
//觀察者
public interface Observer{
void update(float temp, float humidity, float pressure);
}
//佈告板
public class ConditionsPanel : Observer{
private float temperature;
private Subject weatherData;
//構造函數保存subject,並且註冊自己
public ConditionsPanel(Subject weatherData){
this.weatherData = weatherData;
weatherData.registerObserver (this);
}
//觀察者接口規定每個佈告板都必須實現的統一接口
public void update(float temperature, float humidity, float pressure){
this.temperature = temperature;
}
}
設計原則:
1.低耦合
爲了交互對象之間的鬆耦合設計而努力。 針對接口編程讓對象之間的依賴降低,達到鬆耦合的目的。
2.封裝變化
3.針對接口編程,不針對實現編程
4.多用組合,少用繼承