[关闭]
@DevWiki 2015-07-02T21:15:04.000000Z 字数 15154 阅读 1019

Java设计模式---观察者模式

设计模式


更多内容详见:Java设计模式学习笔记

故事概要

概要

故事要从一个业务需求开始:

天气监测站目前可以监测到气温,气压,湿度三种指标,有一个WeatherData类,当前面的三个数据发生变化时,就会调用WeatherData类的setWeatherData()方法,改变天气数据.

现在要求:需要有两个显示装置显示现在的状态和平均状态.当监测的数据有变化时,就更新显示.而且需要提供给第三方的人员可调用这些数据以设置想要的显示装置.如下图:

业务需求图

下面是给出的WeatherData类:

  1. public class WeatherData {
  2. private float temp;
  3. private float humidity;
  4. private float pressure;
  5. public WeatherData(){}
  6. public void setWeatherData(float temp, float humidity, float pressure){
  7. this.temp = temp;
  8. this.humidity = humidity;
  9. this.pressure = pressure;
  10. dataChanged();
  11. }
  12. public void dataChanged(){
  13. //数据发生变化则调用此方法,可在此处填写你的代码
  14. }
  15. public float getTemp() {
  16. return temp;
  17. }
  18. public float getHumidity() {
  19. return humidity;
  20. }
  21. public float getPressure() {
  22. return pressure;
  23. }
  24. }

提取已知条件

目前已知的条件:
1. WeatherData具有三个getter方法,可获取到温度,气压和湿度三个数值.
2. 当监测到新的数据时就会调用dataChanged()方法.
3. 需要实现两个显示器,一个显示当前状况(CurrentConditionsDisplay),一个显示平均状态(AvgStateDisplay).
4. 系统要能扩展,第三方可以组合实现显示器.

简单实现

根据以上前提,可以用以下方法实现:

  1. public void dataChanged(){
  2. //数据发生变化则调用此方法,可在此处填写你的代码
  3. currentConditionsDisplay.update(temp, humidity, pressure);
  4. avgStateDisplay.update(temp, humidity, pressure);
  5. }

其中,CurrentConditionsDisplay和AvgStateDisplay如下:

  1. //显示当前状态
  2. public class CurrentConditionsDisplay{
  3. private float temp;
  4. private float humidity;
  5. private float pressure;
  6. public void update(float temp, float humidity, float pressure) {
  7. this.temp = temp;
  8. this.humidity = humidity;
  9. this.pressure = pressure;
  10. display();
  11. }
  12. public void display(){
  13. //显示当前状态
  14. String displayData = "CurrentConditions[temp=" + temp + ", humidity=" + humidity +
  15. ", pressure="+ pressure + "]";
  16. System.out.println(displayData);
  17. }
  18. }
  19. //显示平均状态
  20. public class AvgStateDisplay {
  21. public void display() {
  22. System.out.println(getShowInfo());
  23. }
  24. private String getShowInfo(){
  25. StringBuilder displayData = new StringBuilder();
  26. if (tempList.size() == 0) {
  27. displayData.append("暂时没有数据...");
  28. return displayData.toString();
  29. }
  30. float tempAve = calculatorAve(tempList);
  31. displayData.append("平均气温:" + tempAve);
  32. float humidityAve = calculatorAve(humidityList);
  33. displayData.append(",平均湿度:" + humidityAve);
  34. float pressureAve = calculatorAve(pressureList);
  35. displayData.append(",平均压强:" + pressureAve);
  36. return displayData.toString();
  37. }
  38. private float calculatorAve(List<Float> dataList){
  39. float sum = 0F;
  40. for (Float float1 : dataList) {
  41. sum = sum + float1;
  42. }
  43. float ave = sum/dataList.size();
  44. return ave;
  45. }
  46. private List<Float> tempList;
  47. private float temp;
  48. private List<Float> humidityList;
  49. private float humidity;
  50. private List<Float> pressureList;
  51. private float pressure;
  52. public void update(float temp, float humidity, float pressure) {
  53. this.temp = temp;
  54. this.humidity = humidity;
  55. this.pressure = pressure;
  56. if (tempList == null) {
  57. tempList = new ArrayList<Float>();
  58. }
  59. tempList.add(temp);
  60. if (humidityList == null) {
  61. humidityList = new ArrayList<Float>();
  62. }
  63. humidityList.add(humidity);
  64. if (pressureList == null) {
  65. pressureList = new ArrayList<Float>();
  66. }
  67. pressureList.add(pressure);
  68. display();
  69. }
  70. }

这不就实现了刚才的功能:
1. 能显示当前状态
2. 能显示平均状态
3. 第三方可以通过WeatherData的dataChanged()方法获取数据,自己任意显示.

有没有问题?

上一篇文章学习了Java设计的原则:

封装变化和面向接口编程

上述的实现中:

  1. public void dataChanged(){
  2. //数据发生变化则调用此方法,可在此处填写你的代码
  3. currentConditionsDisplay.update(temp, humidity, pressure);
  4. avgStateDisplay.update(temp, humidity, pressure);
  5. }

这个里面的3,4两句是变化的,这部分没有封装.而且应该面向接口编程而不是面向具体的类编程,如果增加第三方的显示器,只能修改此处添加代码

认识观察者模式

从订阅报纸开始

报纸的订阅过程一般如下:

观察者模式就和上面的订报纸差不多:

出版者改称为“主题”(Subject),订阅者改称为“观察者”(Observer)

观察者模式

观察者模式

观察者模式

观察者模式

观察者模式

定义观察者模式

定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。

观察者模式

观察者模式的类图

观察者模式类图

从以上类图可以看出,观察者模式的是遵守针对接口编程原则的.

手动实现气象站的观察者模式

1.观察者接口

观察者是一个接口:Observer

  1. public interface Observer {
  2. //用于更新的方法
  3. void update(float temp, float humidity, float pressure);
  4. }

2.观察对象接口

贯彻对象接口有三个作用:
1. 观察者注册为观察者
2. 观察者解除注册
3. 数据更新时通知观察者

  1. public interface Subject {
  2. //注册为观察者
  3. void registerObserver(Observer observer);
  4. //解除注册
  5. void unregisterObserver(Observer observer);
  6. //通知观察者
  7. void notifyObserver();
  8. }

3.新的WeatherData类

其中的setter是给气象站设置数据使用.getter是给第三方获取数据使用

  1. public class WeatherData implements Subject{
  2. private float temp;
  3. private float humidity;
  4. private float pressure;
  5. private List<Observer> observerList;
  6. public WeatherData(){
  7. observerList = new ArrayList<Observer>();
  8. }
  9. public void setWeatherData(float temp, float humidity, float pressure){
  10. this.temp = temp;
  11. this.humidity = humidity;
  12. this.pressure = pressure;
  13. dataChanged();
  14. }
  15. public void dataChanged(){
  16. notifyObserver();
  17. }
  18. public void registerObserver(Observer observer) {
  19. observerList.add(observer);
  20. }
  21. public void unregisterObserver(Observer observer) {
  22. int index = observerList.indexOf(observer);
  23. if (index >= 0) {
  24. observerList.remove(observer);
  25. }
  26. }
  27. public void notifyObserver() {
  28. for (Observer observer : observerList) {
  29. observer.update(temp, humidity, pressure);
  30. }
  31. }
  32. public float getTemp() {
  33. return temp;
  34. }
  35. public void setTemp(float temp) {
  36. this.temp = temp;
  37. }
  38. public float getHumidity() {
  39. return humidity;
  40. }
  41. public void setHumidity(float humidity) {
  42. this.humidity = humidity;
  43. }
  44. public float getPressure() {
  45. return pressure;
  46. }
  47. public void setPressure(float pressure) {
  48. this.pressure = pressure;
  49. }
  50. }

4.显示器接口

显示器接口是用来实现各种显示器的

  1. public interface DisplayElement {
  2. void display();
  3. }

5.显示器的实现类:CurrentConditionsDisplay和AvgStateDisplay类

CurrentConditionsDisplay:当前状态显示器
AvgStateDisplay:平均状态显示器

  1. public class CurrentConditionsDisplay implements Observer, DisplayElement {
  2. private WeatherData weatherData;
  3. public CurrentConditionsDisplay(WeatherData weatherData){
  4. this.weatherData = weatherData;
  5. weatherData.registerObserver(this);
  6. }
  7. public void unregister(){
  8. weatherData.unregisterObserver(this);
  9. }
  10. public void display() {
  11. String displayData = "CurrentConditions[temp=" + temp + ", humidity=" + humidity + ", pressure="
  12. + pressure + "]";
  13. System.out.println(displayData);
  14. }
  15. private float temp;
  16. private float humidity;
  17. private float pressure;
  18. public void update(float temp, float humidity, float pressure) {
  19. this.temp = temp;
  20. this.humidity = humidity;
  21. this.pressure = pressure;
  22. display();
  23. }
  24. }
  25. //---------------------------------------------------------------//
  26. public class AvgStateDisplay implements Observer, DisplayElement{
  27. private WeatherData weatherData;
  28. public AvgStateDisplay(WeatherData weatherData){
  29. this.weatherData = weatherData;
  30. weatherData.registerObserver(this);
  31. }
  32. public void unregister(){
  33. weatherData.unregisterObserver(this);
  34. }
  35. public void display() {
  36. System.out.println(getShowInfo());
  37. }
  38. private String getShowInfo(){
  39. StringBuilder displayData = new StringBuilder();
  40. if (tempList.size() == 0) {
  41. displayData.append("暂时没有数据...");
  42. return displayData.toString();
  43. }
  44. float tempAve = calculatorAve(tempList);
  45. displayData.append("平均气温:" + tempAve);
  46. float humidityAve = calculatorAve(humidityList);
  47. displayData.append(",平均湿度:" + humidityAve);
  48. float pressureAve = calculatorAve(pressureList);
  49. displayData.append(",平均压强:" + pressureAve);
  50. return displayData.toString();
  51. }
  52. private float calculatorAve(List<Float> dataList){
  53. float sum = 0F;
  54. for (Float float1 : dataList) {
  55. sum = sum + float1;
  56. }
  57. float ave = sum/dataList.size();
  58. return ave;
  59. }
  60. private List<Float> tempList;
  61. private float temp;
  62. private List<Float> humidityList;
  63. private float humidity;
  64. private List<Float> pressureList;
  65. private float pressure;
  66. public void update(float temp, float humidity, float pressure) {
  67. this.temp = temp;
  68. this.humidity = humidity;
  69. this.pressure = pressure;
  70. if (tempList == null) {
  71. tempList = new ArrayList<Float>();
  72. }
  73. tempList.add(temp);
  74. if (humidityList == null) {
  75. humidityList = new ArrayList<Float>();
  76. }
  77. humidityList.add(humidity);
  78. if (pressureList == null) {
  79. pressureList = new ArrayList<Float>();
  80. }
  81. pressureList.add(pressure);
  82. display();
  83. }
  84. }

6.测试

测试气象站数据变化时能否通知当前状态显示器和平均状态显示器更新数据

  1. public class WeatherStation {
  2. public static void main(String[] args) {
  3. WeatherData weatherData = new WeatherData();
  4. CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
  5. AvgStateDisplay stateDisplay = new AvgStateDisplay(weatherData);
  6. weatherData.setWeatherData(25.0F, 80F, 1.01F);
  7. try {
  8. Thread.sleep(3000);
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. weatherData.setWeatherData(26.2F, 76F, 1.02F);
  13. try {
  14. Thread.sleep(3000);
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. weatherData.setWeatherData(27.8F, 70F, 1.01F);
  19. }
  20. }

输出结果为:

  1. CurrentConditions[temp=25.0, humidity=80.0, pressure=1.01]
  2. 平均气温:25.0,平均湿度:80.0,平均压强:1.01
  3. CurrentConditions[temp=26.2, humidity=76.0, pressure=1.02]
  4. 平均气温:25.6,平均湿度:78.0,平均压强:1.015
  5. CurrentConditions[temp=27.8, humidity=70.0, pressure=1.01]
  6. 平均气温:26.333334,平均湿度:75.333336,平均压强:1.0133333

7.增加酷热指数的显示器:HeatIndexDisplay

  1. public class HeatIndexDisplay implements Observer, DisplayElement{
  2. private WeatherData weatherData;
  3. public HeatIndexDisplay(WeatherData weatherData){
  4. this.weatherData = weatherData;
  5. weatherData.registerObserver(this);
  6. }
  7. public void unregister(){
  8. weatherData.unregisterObserver(this);
  9. }
  10. @Override
  11. public void display() {
  12. System.out.println("当前酷热指数:" + getHeatIndex());
  13. }
  14. private float getHeatIndex(){
  15. float heatIndex = 0F;
  16. //此处酷热指数计算公式不正确,是随意写的
  17. heatIndex = (float) (temp*Math.PI + humidity*Math.E + pressure*1.01315)/5;
  18. return heatIndex;
  19. }
  20. private float temp;
  21. private float humidity;
  22. private float pressure;
  23. @Override
  24. public void update(float temp, float humidity, float pressure) {
  25. this.temp = temp;
  26. this.humidity = humidity;
  27. this.pressure = pressure;
  28. display();
  29. }
  30. }

8.测试第三方的显示器

  1. public class WeatherStation {
  2. public static void main(String[] args) {
  3. WeatherData weatherData = new WeatherData();
  4. CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
  5. AvgStateDisplay stateDisplay = new AvgStateDisplay(weatherData);
  6. HeatIndexDisplay heatIndexDisplay = new HeatIndexDisplay(weatherData);
  7. weatherData.setWeatherData(25.0F, 80F, 1.01F);
  8. try {
  9. Thread.sleep(3000);
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. }
  13. weatherData.setWeatherData(26.2F, 76F, 1.02F);
  14. try {
  15. Thread.sleep(3000);
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. weatherData.setWeatherData(27.8F, 70F, 1.01F);
  20. }
  21. }

测试结果如下:

  1. CurrentConditions[temp=25.0, humidity=80.0, pressure=1.01]
  2. 平均气温:25.0,平均湿度:80.0,平均压强:1.01
  3. 当前酷热指数:59.40513
  4. CurrentConditions[temp=26.2, humidity=76.0, pressure=1.02]
  5. 平均气温:25.6,平均湿度:78.0,平均压强:1.015
  6. 当前酷热指数:57.98651
  7. CurrentConditions[temp=27.8, humidity=70.0, pressure=1.01]
  8. 平均气温:26.333334,平均湿度:75.333336,平均压强:1.0133333
  9. 当前酷热指数:55.727856

小结

经过以上测试,我们使用了观察者模式实现了:
1. 气象站测试到数据-->发布数据变更--->更新各个不同类型的显示器.
2. 实现了当前状况的显示和平均状态的显示
3. 开发者可是自行实现多种形式的显示器

Java内置的观察者模式

Java内置的主题

Java内部的主题存在java.util包下,其源码如下:

  1. public class Observable {
  2. private boolean changed = false;
  3. private Vector<Observer> obs;
  4. public Observable() {
  5. obs = new Vector<>();
  6. }
  7. public synchronized void addObserver(Observer o) {
  8. if (o == null)
  9. throw new NullPointerException();
  10. if (!obs.contains(o)) {
  11. obs.addElement(o);
  12. }
  13. }
  14. public synchronized void deleteObserver(Observer o) {
  15. obs.removeElement(o);
  16. }
  17. public void notifyObservers() {
  18. notifyObservers(null);
  19. }
  20. public void notifyObservers(Object arg) {
  21. Object[] arrLocal;
  22. synchronized (this) {
  23. if (!changed)
  24. return;
  25. arrLocal = obs.toArray();
  26. clearChanged();
  27. }
  28. for (int i = arrLocal.length-1; i>=0; i--)
  29. ((Observer)arrLocal[i]).update(this, arg);
  30. }
  31. public synchronized void deleteObservers() {
  32. obs.removeAllElements();
  33. }
  34. protected synchronized void setChanged() {
  35. changed = true;
  36. }
  37. protected synchronized void clearChanged() {
  38. changed = false;
  39. }
  40. public synchronized boolean hasChanged() {
  41. return changed;
  42. }
  43. public synchronized int countObservers() {
  44. return obs.size();
  45. }
  46. }

内置的主题类提供:增加观察者,删除观察者,删除所有观察者,提醒某个观察者,提醒所有观察者,获取观察者的数量,设置数据变化等方法.

与自定义的主题不同的是:

  1. java内置的主题是一个类不是一个接口.
  2. java内置的主题必须手动设置数据变化,即setChanged().否则主题不会通知观察者.

Java内置的观察者

java内置的主题在java.util包下,其源码如下:

  1. public interface Observer {
  2. void update(Observable o, Object arg);
  3. }

与自定义的观察者一致.

使用Java内置的观察者模式实现气象站

WeatherData类

  1. public class WeatherData extends Observable{
  2. private float temp;
  3. private float humidity;
  4. private float pressure;
  5. public WeatherData(){}
  6. public void setWeatherData(float temp, float humidity, float pressure){
  7. this.temp = temp;
  8. this.humidity = humidity;
  9. this.pressure = pressure;
  10. dataChanged();
  11. }
  12. public void dataChanged(){
  13. setChanged();
  14. notifyObservers();
  15. }
  16. public float getTemp() {
  17. return temp;
  18. }
  19. public float getHumidity() {
  20. return humidity;
  21. }
  22. public float getPressure() {
  23. return pressure;
  24. }
  25. }

CurrentConditionsDisplay

  1. public class CurrentConditionsDisplay implements Observer, DisplayElement {
  2. private Observable observable;
  3. public CurrentConditionsDisplay(Observable observable){
  4. this.observable = observable;
  5. observable.addObserver(this);
  6. }
  7. public void unregister(){
  8. observable.deleteObserver(this);
  9. }
  10. public void display() {
  11. String displayData = "CurrentConditions[temp=" + temp + ", humidity=" + humidity + ", pressure="
  12. + pressure + "]";
  13. System.out.println(displayData);
  14. }
  15. private float temp;
  16. private float humidity;
  17. private float pressure;
  18. @Override
  19. public void update(Observable o, Object arg) {
  20. if (o instanceof WeatherData) {
  21. WeatherData weatherData = (WeatherData) o;
  22. this.temp = weatherData.getTemp();
  23. this.humidity = weatherData.getHumidity();
  24. this.pressure = weatherData.getPressure();
  25. display();
  26. }
  27. }
  28. }

AvgStateDisplay

  1. public class AvgStateDisplay implements Observer, DisplayElement{
  2. private Observable observable;
  3. public AvgStateDisplay(Observable observable){
  4. observable.addObserver(this);
  5. this.observable = observable;
  6. }
  7. public void unregister(){
  8. observable.deleteObserver(this);
  9. }
  10. public void display() {
  11. System.out.println(getShowInfo());
  12. }
  13. private String getShowInfo(){
  14. StringBuilder displayData = new StringBuilder();
  15. if (tempList.size() == 0) {
  16. displayData.append("暂时没有数据...");
  17. return displayData.toString();
  18. }
  19. float tempAve = calculatorAve(tempList);
  20. displayData.append("平均气温:" + tempAve);
  21. float humidityAve = calculatorAve(humidityList);
  22. displayData.append(",平均湿度:" + humidityAve);
  23. float pressureAve = calculatorAve(pressureList);
  24. displayData.append(",平均压强:" + pressureAve);
  25. return displayData.toString();
  26. }
  27. private float calculatorAve(List<Float> dataList){
  28. float sum = 0F;
  29. for (Float float1 : dataList) {
  30. sum = sum + float1;
  31. }
  32. float ave = sum/dataList.size();
  33. return ave;
  34. }
  35. private List<Float> tempList;
  36. private float temp;
  37. private List<Float> humidityList;
  38. private float humidity;
  39. private List<Float> pressureList;
  40. private float pressure;
  41. @Override
  42. public void update(Observable o, Object arg) {
  43. if (o instanceof WeatherData) {
  44. WeatherData weatherData = (WeatherData) o;
  45. this.temp = weatherData.getTemp();
  46. this.humidity = weatherData.getHumidity();
  47. this.pressure = weatherData.getPressure();
  48. if (tempList == null) {
  49. tempList = new ArrayList<Float>();
  50. }
  51. tempList.add(temp);
  52. if (humidityList == null) {
  53. humidityList = new ArrayList<Float>();
  54. }
  55. humidityList.add(humidity);
  56. if (pressureList == null) {
  57. pressureList = new ArrayList<Float>();
  58. }
  59. pressureList.add(pressure);
  60. display();
  61. }
  62. }
  63. }

HeatIndexDisplay

  1. public class HeatIndexDisplay implements Observer, DisplayElement{
  2. private Observable observable;
  3. public HeatIndexDisplay(Observable observable){
  4. observable.addObserver(this);
  5. this.observable = observable;
  6. }
  7. public void unregister(){
  8. observable.deleteObserver(this);
  9. }
  10. @Override
  11. public void display() {
  12. System.out.println("当前酷热指数:" + getHeatIndex());
  13. }
  14. private float getHeatIndex(){
  15. float heatIndex = 0F;
  16. heatIndex = (float) (temp*Math.PI + humidity*Math.E + pressure*1.01315)/5;
  17. return heatIndex;
  18. }
  19. private float temp;
  20. private float humidity;
  21. private float pressure;
  22. @Override
  23. public void update(Observable o, Object arg) {
  24. if (o instanceof WeatherData) {
  25. WeatherData weatherData = (WeatherData) o;
  26. this.temp = weatherData.getTemp();
  27. this.humidity = weatherData.getHumidity();
  28. this.pressure = weatherData.getPressure();
  29. display();
  30. }
  31. }
  32. }

测试类

  1. public class WeatherStation {
  2. public static void main(String[] args) {
  3. WeatherData weatherData = new WeatherData();
  4. CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
  5. AvgStateDisplay stateDisplay = new AvgStateDisplay(weatherData);
  6. HeatIndexDisplay heatIndexDisplay = new HeatIndexDisplay(weatherData);
  7. weatherData.setWeatherData(25.0F, 80F, 1.01F);
  8. try {
  9. Thread.sleep(3000);
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. }
  13. weatherData.setWeatherData(26.2F, 76F, 1.02F);
  14. try {
  15. Thread.sleep(3000);
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. weatherData.setWeatherData(27.8F, 70F, 1.01F);
  20. }
  21. }

测试结果如下:

  1. 当前酷热指数:59.40513
  2. 平均气温:25.0,平均湿度:80.0,平均压强:1.01
  3. CurrentConditions[temp=25.0, humidity=80.0, pressure=1.01]
  4. 当前酷热指数:57.98651
  5. 平均气温:25.6,平均湿度:78.0,平均压强:1.015
  6. CurrentConditions[temp=26.2, humidity=76.0, pressure=1.02]
  7. 当前酷热指数:55.727856
  8. 平均气温:26.333334,平均湿度:75.333336,平均压强:1.0133333
  9. CurrentConditions[temp=27.8, humidity=70.0, pressure=1.01]

从上面的结果可以看出与自定义的观察者模式显示的一致.

总结

观察者模式的使用过程如下:

  1. 数据变化的对象继承Observable类.在数据变化后调用setChanged()方法.
  2. 观察者类实现Observer接口,并重新update()方法.
  3. 使用时用观察者内部持有的可观察接口注册与解除注册为观察者.
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注