posts - 310, comments - 6939, trackbacks - 0, articles - 3
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          【Head First設計模式】-Observer模式

          Posted on 2008-01-15 10:07 詩特林 閱讀(1866) 評論(2)  編輯  收藏 所屬分類: DesignPattern
           

          Head First設計模式】-Observer模式

           

          一、要完成的任務

          此系統中的三個部分是氣象站(獲取實際氣象數據的物理裝置)、WeatherData對象(追蹤來自氣象站的數據,并更新布告板)和布告板(顯示目前天氣狀況給用戶看)。


           

          二、Observer模式

           

          1、定義觀察者模式

          觀察者模式定義了對象之間的一對多依賴,這樣一來,當一個對象改變狀態時,它的所有依賴者都會收到通知并自動更新。


           

          2.設計氣象站



           

          三、代碼實現

           

          1.定義接口

           

          1Subject接口

          Subject.java

          package com.sterning.ch2_observer;

          public interface Subject {
              
          public void registerObserver(Observer o);
              
          public void removeObserver(Observer o);
              
          public void notifyObservers();
          }


           

          2Observer接口

          Observer.java

          package com.sterning.ch2_observer;

          public interface Observer {
              
          public void update(float temp,float humidity,float pressure);
          }

           

          3Displayment接口

          Displayment.java

          package com.sterning.ch2_observer;

          public interface Displayment {
              
          public void display();
          }

           

           

          2.實現接口

           

          1WeatherData

          WeatherData.java

          package com.sterning.ch2_observer;

          import java.util.ArrayList;

          public class WeatherData implements Subject {
              
          private ArrayList observers;
              
          private float temperature;
              
          private float humidity;
              
          private float pressure;
              
              
          public WeatherData(){
                  observers
          =new ArrayList();
              }

              
              
          public void notifyObservers() {
                  
          for(int i=0;i<observers.size();i++){
                      Observer observer
          =(Observer)observers.get(i);
                      observer.update(temperature, humidity, pressure);
                  }

              }


              
          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 measurementsChanged(){
                  notifyObservers();
              }

              
          public void setMeasurements(float temperature,float humidity,float pressure){
                  
          this.temperature=temperature;
                  
          this.humidity=humidity;
                  
          this.pressure=pressure;
                  measurementsChanged();
              }

          }


           

          2CurrentConditionsDisplay

          CurrentConditionsDisplay.java

          package com.sterning.ch2_observer;

          public class CurrentConditionsDisplay implements Observer, Displayment {
              
          private float temperature;
              
          private float humidity;
              
          private Subject weatherData;
              
              
          public CurrentConditionsDisplay(Subject weatherData){
                  
          this.weatherData=weatherData;
                  weatherData.registerObserver(
          this);
              }

              
              
          public void update(float temp, float humidity, float pressure) {
                  
          this.temperature=temp;
                  
          this.humidity=humidity;
                  display();
              }


              
          public void display() {
                  System.out.println(
          "Current conditions:"+temperature+"F degrees and "+humidity+"% humidity");
              }


          }


           

          3StatisticsDisplay

          StatisticsDisplay.java

          package com.sterning.ch2_observer;

          import java.util.*;

          public class StatisticsDisplay implements Observer, Displayment {
              
          private float maxTemp = 0.0f;
              
          private float minTemp = 200;
              
          private float tempSum= 0.0f;
              
          private int numReadings;
              
          private WeatherData weatherData;

              
          public StatisticsDisplay(WeatherData weatherData) {
                  
          this.weatherData = weatherData;
                  weatherData.registerObserver(
          this);
              }


              
          public void update(float temp, float humidity, float pressure) {
                  tempSum 
          += temp;
                  numReadings
          ++;

                  
          if (temp > maxTemp) {
                      maxTemp 
          = temp;
                  }

           
                  
          if (temp < minTemp) {
                      minTemp 
          = temp;
                  }


                  display();
              }


              
          public void display() {
                  System.out.println(
          "Avg/Max/Min temperature = " + (tempSum / numReadings)
                      
          + "/" + maxTemp + "/" + minTemp);
              }

          }


           

          4ForecastDisplay

          ForecastDisplay.java

          package com.sterning.ch2_observer;

          import java.util.*;

          public class ForecastDisplay implements Observer, Displayment {
              
          private float currentPressure = 29.92f;  
              
          private float lastPressure;
              
          private WeatherData weatherData;

              
          public ForecastDisplay(WeatherData weatherData) {
                  
          this.weatherData = weatherData;
                  weatherData.registerObserver(
          this);
              }


              
          public void update(float temp, float humidity, float pressure) {
                          lastPressure 
          = currentPressure;
                  currentPressure 
          = pressure;

                  display();
              }


              
          public void display() {
                  System.out.print(
          "Forecast: ");
                  
          if (currentPressure > lastPressure) {
                      System.out.println(
          "Improving weather on the way!");
                  }
           else if (currentPressure == lastPressure) {
                      System.out.println(
          "More of the same");
                  }
           else if (currentPressure < lastPressure) {
                      System.out.println(
          "Watch out for cooler, rainy weather");
                  }

              }

          }


           

          3.實現氣象站

          WeatherStation.java

          package com.sterning.ch2_observer;

          public class WeatherStation {
              
          public static void main(String[] args){
                  WeatherData weatherData
          =new WeatherData();
                  
                  CurrentConditionsDisplay currentDisplay
          =new CurrentConditionsDisplay(weatherData);
                  StatisticsDisplay statisticsDisplay 
          = new StatisticsDisplay(weatherData);
                  ForecastDisplay forecastDisplay 
          = new ForecastDisplay(weatherData);
                  
                  weatherData.setMeasurements(
          806530.4f);
                  weatherData.setMeasurements(
          827029.2f);
                  weatherData.setMeasurements(
          789029.2f);        
                  
              }

          }


          評論

          # re: 【Head First設計模式】-Observer模式  回復  更多評論   

          2008-01-15 11:58 by sitinspring
          例子不錯。

          # re: 【Head First設計模式】-Observer模式  回復  更多評論   

          2008-07-01 16:03 by Raul Gong
          為何在StatisticsDisplay和ForecastDisplay中要直接使用WeatherData來申明weatherData,而不是像CurrentConditionsDisplay中那樣使用接口Subject,我覺得應該都使用接口Subject,這樣才符合依賴倒置的原則。不知道我說的對不對,呵呵。
          主站蜘蛛池模板: 左贡县| 深水埗区| 临泉县| 和林格尔县| 舞阳县| 张家港市| 遂昌县| 土默特右旗| 镇沅| 桓台县| 鞍山市| 新宁县| 攀枝花市| 桓仁| 泰来县| 龙井市| 来安县| 德兴市| 尉氏县| 平江县| 沈阳市| 阜城县| 昭觉县| 宝丰县| 顺义区| 哈密市| 若羌县| 雷州市| 博客| 海口市| 台州市| 大理市| 巴彦县| 扶沟县| 定州市| 句容市| 灌云县| 武城县| 高雄县| 普兰店市| 咸宁市|