觀察者模式

觀察者模式java

// 佈告板須要顯示時調用display();
public interface DisplayElement {ide

public void display();this

}spa


//觀察者接口
server

public interface Observer {接口

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

}get


//主題接口
it

public interface Subject {io

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);

}

}
若是驕傲沒有冷冷拍下,又怎懂得要多努力才走的到遠方,若是夢想未曾墜落懸崖危在旦夕,又怎曉得執着的人,擁有隱形的翅膀。                                                                                                                            --------------------------------------------------《最初的夢想》

相關文章
相關標籤/搜索