观察者模式:
1,观察者模式定义了对象之间一对多的关系
2,主题(也就是可观察者)用一个共同的接口来更新观察者
3,观察者和可观察者之间用松耦合方式结合,可观察者不知道观察者细节,只知道观察者实现了观察者接口
4,使用此模式你可以从被观察者处“推”或者“拉”数据,“推”的方式被认为更正确
5,有多个观察者时,不可以依赖特定的通知次序
设计原则
1,找出程序中变化的方面,然后将其和固定不变的方面相分离
2,针对接口编程,不针对实现编程
3,多用组合,少用继承
设计图:
代码实现:
1接口:
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObserver();
}
public interface Observer {
public void update(float temp,float humidity,float pressure);
}
public interface Observer {
public void update(float temp,float humidity,float pressure);
}
2接口实现
public class WeatherData implements Subject {
private ArrayList observers;//建立一个数组来存储观察者
private float temperature;
private float humidity;
private float pressure;
public WeatherData(){
observers = new ArrayList();
}
//对观察者的注册和删除
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
@Override
public void removeObserver(Observer o) {
int i = observers.indexOf(o);
if(i>=0){
observers.remove(i);
}
}
//这里是比较重要的,这是对观察者进行广播
@Override
public void notifyObserver() {
for(int i=0;i<observers.size();i++){
Observer obserrver = (Observer) observers.get(i);
//对观察者进行更新
obserrver.update(temperature, humidity, pressure);
}
}
public void measurementsChanged(){
notifyObserver();
}
public void setMeasurements(float temperature,float humidity,float pressure){
this.humidity = humidity;
this.pressure = pressure;
this.temperature = temperature;
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);
}
@Override
public void display() {
System.out.println("Current conditions:" + temperature + " F degrees and " + humidity + "% humidity");
}
@Override
public void update(float temp, float humidity, float pressure) {
this.temperature = temp;
this.humidity = humidity;
display();
}
}
测试:
public class WeatherStation {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
weatherData.setMeasurements(80, 65, 30.4f);
}
}