观察者模式

观察者模式

// 布告板需要显示时调用display();
public interface DisplayElement {

public void display();

}


//观察者接口

public interface Observer {

public void update(float temp, float humidity, float pressure);

}


//主题接口

public interface Subject {

public void registerObserver(Observer o);

public void removeObserver(Observer o);

public void notifyObservers();

}


//气象资料

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 registerObserver(Observer o) {

observers.add(o);

}

//移除观察者

public void removeObserver(Observer o) {

int i = observers.indexOf(o);

if (i >= 0) {

observers.remove(i);

}

}

//通知所有观察者

public void notifyObservers() {

for (int i = 0; i < observers.size(); i++) {

Observer observer = (Observer) observers.get(i);

observer.update(temperature, humidity, pressure);

}

}

public void measurementsChanged() {

notifyObservers();

}

//调用参数设置气象资料

public void setMeasurements(float temperature, float humidity,

float pressure) {

this.temperature = temperature;

this.humidity = humidity;

this.pressure = pressure;

measurementsChanged();

}

}


//目前状况布告板

public class CurrentConditionsDisplay implements Observer, DisplayElement {

private float temperature;

private float humidity;

private Subject weatherData;

public CurrentConditionsDisplay(Subject weatherData) {

this.weatherData = weatherData;

weatherData.registerObserver(this);

}

public void update(float temperature, float humidity, float pressure) {

this.temperature = temperature;

this.humidity = humidity;

display();

}

public void display() {

System.out.println("Current conditions:" + temperature

+ "F degrees and " + humidity + "% humidity");

}

}



//气象站

public class WeatherStation {

public static void main(String[] args) {

WeatherData weatherData = new WeatherData();

CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(

weatherData);

weatherData.setMeasurements(80, 65, 30.4f);

}

}












如果骄傲没有冷冷拍下,又怎懂得要多努力才走的到远方,如果梦想不曾坠落悬崖千钧一发,又怎晓得执着的人,拥有隐形的翅膀。
                                                                                                                            --------------------------------------------------《最初的梦想》


你可能感兴趣的:(display,import,private,public,interface)