设计模式-观察者模式
Posted hmily555
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式-观察者模式相关的知识,希望对你有一定的参考价值。
观察者模式:定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖都会收到通知并自动更新。
类图:
设计气象站:
代码:
三个接口:Subject、Observer、DisplayElement
/**
* Created by zyzhmily on 2018/5/20.
* 主题
*/
public interface Subject {
public void registerObserver(Observer observer);
public void removeObserver(Observer observer);
public void notifyObserver();
}
/**
* Created by zyzhmily on 2018/5/20.
*/
public interface Observer {
public void update(float temperature,float humidity,float pressure);
}
/**
* Created by zyzhmily on 2018/5/20.
*/
public interface DisplayElement {
public void display();
}
WeatherData:
/**
* Created by zyzhmily on 2018/5/20.
*/
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 observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
int i=observers.indexOf(observer);
if (i>=0){
observers.remove(i);
}
}
@Override
public void notifyObserver() {
for (int i=0;i
Observer observer= (Observer) observers.get(i);
observer.update(temperature,humidity,pressure);
}
}
public void measurementschanged(){
notifyObserver();
}
public void setMeasurements(float temperature,float humidity,float pressure){
this.temperature=temperature;
this.humidity=humidity;
this.pressure=pressure;
measurementschanged();
}
}
CurrentConditionsDisplay:
/**
* Created by zyzhmily on 2018/5/20.
*/
public class CurrentConditionsDisplay implements Observer,DisplayElement{
private float temperature;
private float humidity;
private Subject weatherData;
public CurrentConditionsDisplay(Subject subject) {
this.weatherData=subject;
weatherData.registerObserver(this);
}
@Override
public void update(float temperature, float humidity, float pressure) {
this.temperature=temperature;
this.humidity=humidity;
display();
}
@Override
public void display() {
System.out.println("Current conditions: "+temperature+" F degree and "+humidity+" % humidity");
}
}
测试类:
/**
* Created by zyzhmily on 2018/5/19.
*/
public class PatternObserver {
public static void main(String[] args){
WeatherData weatherData=new WeatherData();
CurrentConditionsDisplay currentConditionsDisplay=new CurrentConditionsDisplay(weatherData);
weatherData.setMeasurements(80,65,30.4f);
}
}
本文来自 《Head First 设计模式》
以上是关于设计模式-观察者模式的主要内容,如果未能解决你的问题,请参考以下文章