设计模式-观察者模式

1. 利用Java 内置的类和接口实现观察者模式
public class WeatherData extends Observable {

	private float temperature;
	private float humidity;
	private float pressure;
	
	private String data = "zhangzhaoyu";
	
	public WeatherData() {}
	
	public void measurementsChanged() {
		super.setChanged();
		super.notifyObservers(data);
	}
	
	public void setMeasurements(float temperature, float humidity,
			float pressure) {
		this.temperature = temperature;
		this.humidity = humidity;
		this.pressure = pressure;
		
		measurementsChanged();
	}
	
	public float getTemperature() {
		return this.temperature;
	}
	
	public float getHumidity() {
		return this.humidity;
	}
	
	public float getPressure() {
		return this.pressure;
	}
}

2. 观察者实现的代码
public class CurrentDisplay implements Observer, DisplayElement {

	Observable observable;
	private float temperature;
	private float humidity;
	
	public CurrentDisplay(Observable observable) {
		this.observable = observable;
		observable.addObserver(this);
	}
	
	@Override
	public void update(Observable o, Object arg) {
		if (o instanceof WeatherData) {
			WeatherData weatherData = (WeatherData) o;
			this.temperature = weatherData.getTemperature();
			this.humidity = weatherData.getHumidity();
			
			display();
		}
	}

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

}
 

public class ForecastDisplay implements Observer, DisplayElement {

	Observable observable;
	private float temperature;
	private float humidity;
	private float pressure;
	
	private String data = null;
	
	public ForecastDisplay(Observable _observable) {
		this.observable = _observable;
		this.observable.addObserver(this);
	}
	
	@Override
	public void update(Observable o, Object arg) {
		if (o instanceof WeatherData) {
			WeatherData data = (WeatherData) o;
			this.temperature = data.getTemperature();
			this.humidity = data.getHumidity();
			this.pressure = data.getPressure();
			this.data = (String) arg;
			display();
		}
	}

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

}
 

3. 测试Client类
public class Client {

	public static void main(String[] args) {
		
		WeatherData observable = new WeatherData();
		CurrentDisplay currentDisplay = new CurrentDisplay(observable);
		ForecastDisplay forecastDisplay = new ForecastDisplay(observable);
		
		observable.setMeasurements(10f, 34.5f, 78.9f);
	}

}
 

你可能感兴趣的:(设计模式)