详细介绍:观察者模式(Observer Pattern)定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。
2025-10-22 19:58 tlnshuju 阅读(0) 评论(0) 收藏 举报1. 模式定义
观察者模式(Observer Pattern)定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。
2. 核心组件
2.1 Subject(主题/被观察者)
public interface Subject {
void registerObserver(Observer observer);
// 注册观察者
void removeObserver(Observer observer);
// 移除观察者
void notifyObservers();
// 通知所有观察者
}
2.2 Observer(观察者)
public interface Observer {
void update(Object data);
// 接收更新通知
}
3. 完整实现示例
3.1 具体主题类
import java.util.*;
public class WeatherStation
implements Subject {
private List<
Observer> observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherStation() {
observers = new ArrayList<
>();
}
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
System.out.println("观察者已注册");
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
System.out.println("观察者已移除");
}
@Override
public void notifyObservers() {
WeatherData data = new WeatherData(temperature, humidity, pressure);
for (Observer observer : observers) {
observer.update(data);
}
}
// 天气数据改变时调用
public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}
private void measurementsChanged() {
notifyObservers();
}
// 天气数据类
public static class WeatherData
{
private final float temperature;
private final float humidity;
private final float pressure;
public WeatherData(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
}
// getters
public float getTemperature() {
return temperature;
}
public float getHumidity() {
return humidity;
}
public float getPressure() {
return pressure;
}
}
}
3.2 具体观察者类
// 当前天气显示板
public class CurrentConditionsDisplay
implements Observer {
private String name;
public CurrentConditionsDisplay(String name) {
this.name = name;
}
@Override
public void update(Object data) {
if (data instanceof WeatherStation.WeatherData) {
WeatherStation.WeatherData weatherData = (WeatherStation.WeatherData) data;
display(weatherData);
}
}
private void display(WeatherStation.WeatherData data) {
System.out.println(name + " - 当前天气:");
System.out.println("温度:" + data.getTemperature() + "°C");
System.out.println("湿度:" + data.getHumidity() + "%");
System.out.println("气压:" + data.getPressure() + " hPa");
System.out.println("------------------------");
}
}
// 统计显示板
public class StatisticsDisplay
implements Observer {
private List<
Float> temperatures = new ArrayList<
>();
@Override
public void update(Object data) {
if (data instanceof WeatherStation.WeatherData) {
WeatherStation.WeatherData weatherData = (WeatherStation.WeatherData) data;
temperatures.add(weatherData.getTemperature());
display();
}
}
private void display() {
float avg = (float) temperatures.stream().mapToDouble(Float::doubleValue).average().orElse(0);
float max = temperatures.stream().max(Float::compare).orElse(0f);
float min = temperatures.stream().min(Float::compare).orElse(0f);
System.out.println("温度统计:");
System.out.println("平均温度:" + String.format("%.1f", avg) + "°C");
System.out.println("最高温度:" + max + "°C");
System.out.println("最低温度:" + min + "°C");
System.out.println("------------------------");
}
}
4. 使用示例
public class WeatherStationDemo
{
public static void main(String[] args) {
// 创建天气站
WeatherStation weatherStation = new WeatherStation();
// 创建观察者
CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay("显示板1");
CurrentConditionsDisplay currentDisplay2 = new CurrentConditionsDisplay("显示板2");
StatisticsDisplay statisticsDisplay = new StatisticsDisplay();
// 注册观察者
weatherStation.registerObserver(currentDisplay);
weatherStation.registerObserver(currentDisplay2);
weatherStation.registerObserver(statisticsDisplay);
// 更新天气数据
System.out.println("=== 第一次天气更新 ===");
weatherStation.setMeasurements(25.5f, 65f, 1013.2f);
System.out.println("\n=== 第二次天气更新 ===");
weatherStation.setMeasurements(28.0f, 70f, 1012.8f);
// 移除一个观察者
weatherStation.removeObserver(currentDisplay2);
System.out.println("\n=== 第三次天气更新(移除显示板2后) ===");
weatherStation.setMeasurements(22.3f, 60f, 1014.1f);
}
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/943692.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!相关文章
LeeCode_226反转二叉树
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
示例 1:输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
//法一:
class Solution {
public:TreeNode* invertTree(TreeNode* root){if(root =…
TRAE 设计团队如何玩转 Vibe Coding(下)|设计工具生成与提效篇
资料来源:火山引擎-开发者社区本内容分为上下两篇,主要和大家分享 TRAE 设计团队基于 TRAE 工具的 Vibe Coding 探索实践,包括三类场景的搭建和价值收益的案例,帮助设计师探索如何通过 Vibe Coding 放大设计价值 /…
衡量效率,质量,运维的效率指标
目录背景和价值一、效率类指标(一)开发效率(二)运维效率二、质量类指标(一)代码质量(二)产品质量(三)测试质量(四)运维质量参考资料
背景和价值
在IT团队中,衡量效率和质量的指标可从多个维度进行定义,以…
2025多校冲刺CSP模拟赛7 总结
比赛:2025多校冲刺CSP模拟赛7
日期:\(25.10.22\),场地:\(\text{accoder}\),排名:\(56/73\)!
估分:\(30+0+[80,100]+0=110\)
终分:\(30+0+80+0=110\)
应该得分:\(100+100+[80,100]+?=280\)
失分
比赛决策问题…
详细介绍:wpf之 Popup
详细介绍:wpf之 Popuppre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", &quo…
结对项目-生成四则运算
这个作业属于哪个课程
https://edu.cnblogs.com/campus/gdgy/Class34Grade23ComputerScience/这个作业要求在哪里
https://edu.cnblogs.com/campus/gdgy/Class34Grade23ComputerScience/homework/13479姓名
学号
GitHu…
CSS3 超实用属性:pointer-events (可穿透图层的鼠标事件)
🧑💻 写在开头
点赞 + 收藏 === 学会🤣🤣🤣
CSS3 pointer-events 属性:实现可穿透图层的鼠标事件
在网页开发中,我们通常会遇到多个元素重叠的情况。在这种情况下,如何使得被遮挡的元素仍然能够响应鼠标…
C++开源库使用:nlohmann/json - 指南
C++开源库使用:nlohmann/json - 指南pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Mona…
实用指南:JAVA学习-预科部分(路线、博客、预备基础)
pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …
【比赛记录】2025CSP+NOIP 冲刺模拟赛合集Ⅱ
2025CSP-S模拟赛65(HZOJ CSP-S模拟37)A
B
C
D
Sum
Rank100
40
15
-
155
7/12HZOJ 上也有这场比赛,但我没看见。放过去大概是个 14/24 左右吧。
A. gcd&xor (gcdxor)
首先打表,发现对于所有合法的 \((x,y)\),都…
取证-windbg和dmp,以及文件分析基本流程
.dmp文件及Dump Flie,是一种内存快照文件
说到内存快照就不得不提一下文件类型
说明
常见用途.raw
原始磁盘映像文件(Raw Image),完整保存磁盘或内存的原始二进制数据。
虚拟机快照、数字取证、系统备份。.dmp
内存…
20232422 2025-2026-1 《网络与系统攻防技术》实验二实验报告
后门原理与实践
1.1实验内容
这次的实验主要练了几种获取主机操作权限和收集信息的方法。先是用netcat配合Linux的cron定时任务,还有socat搭配系统任务计划,分别搞到了主机的操作Shell,拿到了控制主机的入口。然后用…
羊驼二次免疫的六大风险:纳米抗体制备不可忽视的 “隐形陷阱”
随着纳米抗体在肿瘤治疗、病原体检测、工业酶固定化等领域的应用拓展,对羊驼免疫及 VHH 筛选的需求持续攀升。羊驼因饲养、运输、免疫成本显著高于小鼠、兔子,市场上逐渐出现 “二次免疫” 操作 —— 即利用已免疫过…
完整教程:C++项目:仿muduo库高并发服务器-------connection模块
完整教程:C++项目:仿muduo库高并发服务器-------connection模块pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "…
深入解析:线性代数 SVD | 令人困扰的精度 1
深入解析:线性代数 SVD | 令人困扰的精度 1pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", &qu…
【最终章】-串口收发指令处理器-Verilog语法学习EP12 - 教程
pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …