《Head First设计模式》学习-Observer模式

来源:互联网 发布:类似枭臣小说知乎 编辑:程序博客网 时间:2024/06/05 08:53
 
《Head First设计模式》学习-Observer模式
《Head First设计模式》学习-Observer模式

 

 

下载源代码


〖 作者:诗特林 〗〖 大小:3K 〗〖 发布日期:2008-01-21 〗〖 浏览:1 〗
<script type="text/javascript"><!--google_ad_client = "pub-1832179689702023";google_ad_width = 728;google_ad_height = 90;google_ad_format = "728x90_as";google_ad_type = "text_image";google_ad_channel ="";//--></script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script> <iframe name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-1832179689702023&amp;dt=1200993351167&amp;lmt=1200898694&amp;format=728x90_as&amp;output=html&amp;correlator=1200993351167&amp;url=http%3A%2F%2Fwww.java3z.com%2Fcwbwebhome%2Farticle%2Farticle2%2F21045.html%3Fid%3D1789&amp;ad_type=text_image&amp;ref=http%3A%2F%2Fwww.baidu.com%2Fs%3Flm%3D0%26si%3D%26rn%3D10%26ie%3Dgb2312%26ct%3D0%26wd%3Dobserver%2B%2B%2B%25C4%25A3%25CA%25BD%26pn%3D10%26ver%3D0%26cl%3D3&amp;cc=100&amp;ga_vid=227957719.1200993351&amp;ga_sid=1200993351&amp;ga_hid=515322661&amp;flash=9&amp;u_h=1024&amp;u_w=1280&amp;u_ah=994&amp;u_aw=1280&amp;u_cd=32&amp;u_tz=-480&amp;u_java=true" frameborder="0" width="728" scrolling="no" height="90" allowtransparency="allowtransparency"></iframe>

一、要完成的任务

此系统中的三个部分是气象站(获取实际气象数据的物理装置)、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);        
        
    }

}

原创粉丝点击