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

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

          Posted on 2008-01-15 10:07 詩特林 閱讀(1863) 評論(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,這樣才符合依賴倒置的原則。不知道我說的對不對,呵呵。
          主站蜘蛛池模板: 桐梓县| 凤翔县| 晋州市| 原平市| 榆社县| 通海县| 常德市| 彰武县| 扶绥县| 贺兰县| 阿城市| 西平县| 思茅市| 江北区| 洪泽县| 岳西县| 贵德县| 洛川县| 阆中市| 长沙县| 岳阳县| 临湘市| 芦溪县| 万荣县| 仁怀市| 宣化县| 阳朔县| 清原| 新余市| 南投市| 余姚市| 岚皋县| 新乐市| 南昌县| 潼南县| 重庆市| 定日县| 伊吾县| 车险| 育儿| 崇礼县|