一:原理就是观察者设计模式的原理直接上图和代码
WeatherData(主题接口实现)
1 public class WeatherData extends Observable { 2 private float temperature; 3 private float humidity; 4 private float pressure; 5 6 public WeatherData() { 7 } 8 9 public void measurementsChanged() { 10 setChanged(); 11 notifyObservers(); 12 } 13 14 public void setMeasurements(float temperature, float humidity, float pressure) { 15 this.temperature = temperature; 16 this.humidity = humidity; 17 this.pressure = pressure; 18 measurementsChanged(); 19 } 20 21 public float getTemperature() { 22 return temperature; 23 } 24 25 public float getHumidity() { 26 return humidity; 27 } 28 29 public float getPressure() { 30 return pressure; 31 } 32 }
isplayElement.java(展示接口)
public interface DisplayElement {
public void display();
}
CurrentConditionsDisplay.java(观察者实现类)
package com.DesignPatterns.ab.observer2; import java.util.Observable; import java.util.Observer; public class CurrentConditionsDisplay implements Observer, DisplayElement { Observable observable; private float temperature; private float humidity; public CurrentConditionsDisplay(Observable observable) { this.observable = observable; observable.addObserver(this); } public void update(Observable obs, Object arg) { if (obs instanceof WeatherData) { WeatherData weatherData = (WeatherData) obs; this.temperature = weatherData.getTemperature(); this.humidity = weatherData.getHumidity(); display(); } } public void display() { System.out.println("Current conditions: " + temperature + "F degrees and " + humidity + "% humidity"); } } |
Test.java(测试)
- @date 2018年9月20日 对比见精髓: 一,注册和上面的差不多,只不多是接口改成抽象类了 二,主题修改通知观察者
- 现在观察者已经注册完毕了,现在我们调用主题的实现类里面的参数修改的方法,修改会调用统一定义的方
法(update),
|
其它的类都由jar包给实现类的。
原文地址:https://www.cnblogs.com/qingruihappy/p/9693367.html