| 1) 气象站可以将每天测量到的温度,湿度,气压等等以公告的形式发布出去(比如发布到自己的网站或第三方)。 |
| 2) 需要设计开放型API,便于其他第三方也能接入气象站获取数据。 |
| 3) 提供温度、气压和湿度的接口 |
| 4) 测量数据更新时,要能实时的通知给第三方 |
| 0) 设计出一个WeatherData类作为第三方网站 |
| 1) 通过getXxx方法,可以让第三方接入,并得到相关信息. |
| 2) 当数据有更新时,气象站通过调用dataChange() 去更新数据,当第三方再次获取时,就能得到最新数据,当然也可以推送 |

-
气象站向第三方推送数据

-
代码实现
| package com.atguigu.observer; |
| |
| |
| |
| public class CurrentConditions { |
| |
| private float temperature; |
| |
| private float pressure; |
| |
| private float humidity; |
| |
| |
| public void update(float temperature, float pressure, float humidity) { |
| this.temperature = temperature; |
| this.pressure = pressure; |
| this.humidity = humidity; |
| display(); |
| } |
| |
| |
| public void display() { |
| System.out.println("***Today mTemperature: " + temperature + "***"); |
| System.out.println("***Today mPressure: " + pressure + "***"); |
| System.out.println("***Today mHumidity: " + humidity + "***"); |
| } |
| } |
| |
| package com.atguigu.observer; |
| |
| |
| |
| |
| |
| |
| public class WeatherData { |
| |
| private float temperatrue; |
| |
| private float pressure; |
| |
| private float humidity; |
| |
| private CurrentConditions currentConditions; |
| |
| |
| public WeatherData(CurrentConditions currentConditions) { |
| this.currentConditions = currentConditions; |
| } |
| |
| public float getTemperature() { |
| return temperatrue; |
| } |
| |
| public float getPressure() { |
| return pressure; |
| } |
| |
| public float getHumidity() { |
| return humidity; |
| } |
| |
| public void dataChange() { |
| |
| currentConditions.update(getTemperature(), getPressure(), getHumidity()); |
| } |
| |
| |
| public void setData(float temperature, float pressure, float humidity) { |
| this.temperatrue = temperature; |
| this.pressure = pressure; |
| this.humidity = humidity; |
| |
| dataChange(); |
| } |
| } |
| |
| package com.atguigu.observer; |
| public class Client { |
| public static void main(String[] args) { |
| |
| CurrentConditions currentConditions = new CurrentConditions(); |
| |
| WeatherData weatherData = new WeatherData(currentConditions); |
| |
| weatherData.setData(30, 150, 40); |
| |
| System.out.println("============天气情况变化============="); |
| weatherData.setData(40, 160, 20); |
| } |
| } |
| |
| public void dataChange() { |
| currentConditions.update(getTemperature(), getPressure(), getHumidity()); |
| } |
| |
| 1) 其他第三方接入气象站获取数据的问题 |
| 2) 无法在运行时动态的添加第三方 (新浪网站) |
| 3) 违反ocp原则=>观察者模式 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?