设计模式(十八)——观察者模式(JDK Observable源码分析)
1 天气预报项目需求,具体要求如下:
1) 气象站可以将每天测量到的温度,湿度,气压等等以公告的形式发布出去(比如发布到自己的网站或第三方)。
2) 需要设计开放型 API,便于其他第三方也能接入气象站获取数据。
3) 提供温度、气压和湿度的接口
4) 测量数据更新时,要能实时的通知给第三方
2 天气预报设计方案 1-普通方案
WeatherData 类
- 传统的设计方案


- 代码实现
package com.lin.observer; /**
* 显示当前天气情况(可以理解为气象站的网站)
* @Description:
* @author LinZM
* @date 2021-2-7 12:49:27
* @version V1.8
*/
public class CurrentConditions { // 温度,气压,湿度
private float temperatrue; private float pressure; private float humidity; // 更新天气情况
public void update(float temperature, float pressure, float humidity) {
this.temperatrue = temperature;
this.pressure = pressure;
this.humidity = humidity;
display();
} public void display(){
System.out.println("===Today's temperature: "+temperatrue+"===");
System.out.println("===Today's pressure: "+pressure+"===");
System.out.println("===Today's humidity: "+humidity+"===");
} }
package com.lin.observer; /*
* 类是核心 1. 包含最新的天气情况信息 2. 含有 CurrentConditions 对象 3. 当数据有更新时,就主动的调用
* CurrentConditions 对象 update 方法(含 display), 这样他们(接入方)就看到最新的信息
*/ 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() { //调用 接入方的 update
currentConditions.update(getTemperature(), getPressure(), getHumidity());
} //当数据有更新时,就调用 setData
public void setData(float temperature, float pressure, float humidity) {
this.temperatrue = temperature;
this.pressure = pressure;
this.humidity = humidity;
//调用 dataChange, 将最新的信息 推送给 接入方 currentConditions
dataChange();
}
}
package com.lin.observer;
public class Client {
public static void main(String[] args) {
CurrentConditions currentConditions = new CurrentConditions();
WeatherData weatherData = new WeatherData(currentConditions);
weatherData.setData(10, 20, 3);
}
}

- 问题分析
1) 其他第三方接入气象站获取数据的问题
2) 无法在运行时动态的添加第三方 (新浪网站)
3) 违反 ocp 原则=>观察者模式
//在 WeatherData 中,当增加一个第三方,都需要创建一个对应的第三方的公告板对象,并加入到 dataChange, 不利于维护,也不是动态加入
public void dataChange() {
currentConditions.update(getTemperature(), getPressure(), getHumidity());
}
3 观察者模式原理
1) 观察者模式类似订牛奶业务
2) 奶站/气象局:Subject
3) 用户/第三方网站:Observer
- Subject:登记注册、移除和通知
1) registerObserver 注 册
2) removeObserver 移 除
3) notifyObservers() 通知所有的注册的用户,根据不同需求,可以是更新数据,让用户来取,也可能是实施推送, 看具体需求定
- Observer:接收输入
- 观察者模式:对象之间多对一依赖的一种设计方案,被依赖的对象为 Subject,依赖的对象为 Observer,Subject
通知 Observer 变化,比如这里的奶站是 Subject,是 1 的一方。用户时 Observer,是多的一方。
4 观察者模式解决天气预报需求
类图说明

代码实现
package com.lin.observer.plus;
public interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObserver();
}
package com.lin.observer.plus; import java.util.ArrayList; /*
* 类是核心 1. 包含最新的天气情况信息 2. 含有 CurrentConditions 对象 3. 当数据有更新时,就主动的调用
* CurrentConditions 对象 update 方法(含 display), 这样他们(接入方)就看到最新的信息
*/ public class WeatherData implements Subject{ private float temperatrue;
private float pressure;
private float humidity;
private ArrayList<Observer> observers; //加入新的第三方 public WeatherData() {
observers = new ArrayList<Observer>();
} public float getTemperature() {
return temperatrue;
} public float getPressure() {
return pressure;
} public float getHumidity() {
return humidity;
} public void dataChange() { //调用 接入方的 update
//currentConditions.update(getTemperature(), getPressure(), getHumidity());
notifyObserver();
} //当数据有更新时,就调用 setData
public void setData(float temperature, float pressure, float humidity) {
this.temperatrue = temperature;
this.pressure = pressure;
this.humidity = humidity;
//调用 dataChange, 将最新的信息 推送给 接入方 currentConditions
dataChange();
} @Override
public void registerObserver(Observer o) {
observers.add(o); } @Override
public void removeObserver(Observer o) {
if(observers.contains(o)) {
observers.remove(o);
}
} @Override
public void notifyObserver() {
for (int i = 0; i < observers.size(); i++) {
observers.get(i).update(temperatrue, pressure, humidity);
}
}
}
package com.lin.observer.plus;
public interface Observer {
void update(float temperatrue, float pressure, float humidity);
}
package com.lin.observer.plus;
public class CurrentConditions implements Observer{
// 温度,气压,湿度
private float temperatrue;
private float pressure;
private float humidity;
// 更新天气情况
public void update(float temperature, float pressure, float humidity) {
this.temperatrue = temperature;
this.pressure = pressure;
this.humidity = humidity;
display();
}
public void display(){
System.out.println("===Today's temperature: "+temperatrue+"===");
System.out.println("===Today's pressure: "+pressure+"===");
System.out.println("===Today's humidity: "+humidity+"===");
}
}
package com.lin.observer.plus;
public class BaiDu implements Observer{
// 温度,气压,湿度
private float temperatrue;
private float pressure;
private float humidity;
// 更新天气情况
public void update(float temperature, float pressure, float humidity) {
this.temperatrue = temperature;
this.pressure = pressure;
this.humidity = humidity;
display();
}
public void display() {
System.out.println("===BaiDu's temperature: " + temperatrue + "===");
System.out.println("===BaiDu's pressure: " + pressure + "===");
System.out.println("===BaiDu's humidity: " + humidity + "===");
}
}
package com.lin.observer.plus;
public class Client {
public static void main(String[] args) {
// 创建一个WeatherData
WeatherData weatherData = new WeatherData();
// 创建观察者
CurrentConditions currentConditions = new CurrentConditions();
BaiDu baiDu = new BaiDu();
// 注册
weatherData.registerObserver(currentConditions);
weatherData.registerObserver(baiDu);
// 测试
System.out.println("通知各个注册的观察者:");
weatherData.setData(23, 12, -0.4f);
}
}

观察者模式的好处
1) 观察者模式设计后,会以集合的方式来管理用户(Observer),包括注册,移除和通知。
2) 这样,我们增加观察者(这里可以理解成一个新的公告板),就不需要去修改核心类 WeatherData 不会修改代码, 遵守了 ocp 原则。
5 观察者模式在 Jdk 应用的源码分析
1) Jdk 的 Observable 类就使用了观察者模式
2) 代码分析+模式角色分析

3) 模式角色分析
- Observable 的作用和地位等价于 我们前面讲过 Subject
- Observable 是类,不是接口,类中已经实现了核心的方法 ,即管理 Observer 的方法 add.. delete .. notify...
- Observer 的作用和地位等价于我们前面讲过的 Observer, 有 update
- Observable 和 Observer 的使用方法和前面讲过的一样,只是 Observable 是类,通过继承来实现观察者模式
仅供参考,有错误还请指出!
有什么想法,评论区留言,互相指教指教。
设计模式(十八)——观察者模式(JDK Observable源码分析)的更多相关文章
- JDK Collection 源码分析(2)—— List
JDK List源码分析 List接口定义了有序集合(序列).在Collection的基础上,增加了可以通过下标索引访问,以及线性查找等功能. 整体类结构 1.AbstractList 该类作为L ...
- JDK AtomicInteger 源码分析
@(JDK)[AtomicInteger] JDK AtomicInteger 源码分析 Unsafe 实例化 Unsafe在创建实例的时候,不能仅仅通过new Unsafe()或者Unsafe.ge ...
- 第十篇:Spark SQL 源码分析之 In-Memory Columnar Storage源码分析之 query
/** Spark SQL源码分析系列文章*/ 前面讲到了Spark SQL In-Memory Columnar Storage的存储结构是基于列存储的. 那么基于以上存储结构,我们查询cache在 ...
- 十、Spring之BeanFactory源码分析(二)
Spring之BeanFactory源码分析(二) 前言 在前面我们简单的分析了BeanFactory的结构,ListableBeanFactory,HierarchicalBeanFactory,A ...
- 【十八】php文件下载源码
index.php <!DOCTYPE html> <html> <head> <title></title> <meta chars ...
- JDK Collection 源码分析(1)—— Collection
JDK Collection JDK Collection作为一个最顶层的接口(root interface),JDK并不提供该接口的直接实现,而是通过更加具体的子接口(sub interface ...
- JDK Collection 源码分析(3)—— Queue
@(JDK)[Queue] JDK Queue Queue:队列接口,对于数据的存取,提供了两种方式,一种失败会抛出异常,另一种则返回null或者false. 抛出异常的接口:add,remove ...
- Netty源码分析 (八)----- write过程 源码分析
上一篇文章主要讲了netty的read过程,本文主要分析一下write和writeAndFlush. 主要内容 本文分以下几个部分阐述一个java对象最后是如何转变成字节流,写到socket缓冲区中去 ...
- ABP源码分析一:整体项目结构及目录
ABP是一套非常优秀的web应用程序架构,适合用来搭建集中式架构的web应用程序. 整个Abp的Infrastructure是以Abp这个package为核心模块(core)+15个模块(module ...
随机推荐
- pandas 写csv 操作
pandas 写csv 操作 def show_history(self): df = pd.DataFrame() df['Time'] = pd.Series(self.time_hist) df ...
- 绝对定位上下左右都为0 margin为auto为什么能居中
老规矩,先来一段废话,我大学刚入门的时候觉得CSS很简单,记一记就会了,不就是盒模型嘛,现在想来觉得自己那时候真的很自以为是哈哈.但是随着工作沉淀,我明白了任何技术都有着它的深度和广度,正是因为不少人 ...
- 登陆到 SAP 系统后的用户出口
增强类型:smod 增强名称:SUSR0001 组件(退出功能模块):EXIT_SAPLSUSF_001 功能:用户每次登陆SAP系统后都会调用这个SUSR0001增强,可以在FUNCTION EXI ...
- 渗透测试中期--漏洞复现--MS08_067
靶机:Win2k3 10.10.10.130 攻击机:BT5 10.10.10.128 一:nmap 查看WinK3是否开放端口3389 开放3389方法:我的电脑->属性-&g ...
- jQ实现图片无缝轮播
在铺页面的过程中,总是会遇到轮播图需要处理,一般我是会用swiper来制作,但总会有哪个几个个例需要我自己来写功能,这里制作了一个jq用来实现图片无缝轮播的dome,分享给大家ヽ( ̄▽ ̄)ノ. dom ...
- Py-re正则模块,log模块,config模块,哈希加密
9.re正则表达式模块,用于字符串的模糊匹配 元字符: 第一:点为通配符 用.表示匹配除了换行符以外的所有字符 import re res=re.findall('a..x','adsxwassxdd ...
- JVM(三)从JVM源码角度看类加载器层级关系和双亲委派
类加载器我们都知道有如下的继承结构,这个关系只是逻辑上的父子关系. 我们一直听说引导类加载器没有实体,为什么没有实体呢? 因为引导类加载器只是一段C++代码并不是什么实体类,所谓的引导类加载器就是那一 ...
- 安卓开发视频教程!想找工作的你还不看这份资料就晚了!Android校招面试指南
前言 准备面试其实已经准备了挺久了,当时打算面试准备了差不多以后,跟公司谈谈涨薪的事情,谈不拢的话,就年后直接找其他的公司.谁想到婚假还没休完,老板就在公司宣布了撤出上海的决定,愿意去深圳的就去,不愿 ...
- linux通过ntp同步时间
1.安装服务 yum install ntp ##安装ntp服务,这个和ntpdate不一样哦,用这个比较好 systemctl start ntpd.service ###启动服务 systemct ...
- 在vCenter Server中添加ESXi 主机失败的问题
报错:出现了常规系统错误: Timed out waiting for vpxa to start 报错是这个,我看了下vcenter的版本是6.5,如图右上,这个报错是因为我ESXI主机是6.7的, ...