设计模式(十八)——观察者模式(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 ...
随机推荐
- session、cookie、token的区别
从安全性优先级来说: 1.优先级 Cookie<session<token 2. 安全性 Cookie: ①cookie不是很安全,别人可以分析存放在本地的cookie并进行cookie欺 ...
- innobackupex: Connecting to MySQL server with DSN 'dbi:mysql
[root@ma src]# innobackupex --user=root /root/backup --no-timestamp InnoDB Backup Utility v1.5.1-xtr ...
- SWPU2019
一.题目打开介绍 这是题目本身打开的样子,继续进入题目 二.做题 简单的登陆界面和注册界面,没有sql注入已经尝试 申请发布广告 习惯性的测试 然后开始尝试注入,抓包, 两个都要,经过union注入判 ...
- css全站变灰
2020年4月4日全国哀悼日这一天,我发现不少网址都变灰了,我第一想法就是怎么做到的?不可能换素材整个网址重做一遍吧?后面发现是用的其实是css的filter滤镜: grayscale可以将图像转化为 ...
- layui表格数据统计
//执行一个 table 实例 table.render({ elem: '#demo' ,height: 420 ,url: '/demo/table/user/' //数据接口 ,title: ' ...
- 抓包一张tcpdump小抄就够了
作者简介 李先生(Lemon),高级运维工程师(自称),SRE专家(目标),梦想在35岁买一辆保时捷.喜欢钻研底层技术,认为底层基础才是王道.一切新技术都离不开操作系统(CPU.内存.磁盘).网络等. ...
- jQuery 真伪数组的转换
//真数组转换伪数组 var arr = [1,3,5,7,9]; var obj = {}; [].push.apply(obj,arr); console.log(obj) //伪数组转真数组 v ...
- gRPC Motivation and Design Principles | gRPC https://grpc.io/blog/principles/
gRPC Motivation and Design Principles | gRPC https://grpc.io/blog/principles/
- 等待 Redis 应答 Redis pipeline It's not just a matter of RTT
小结: 1.When pipelining is used, many commands are usually read with a single read() system call, and ...
- 洛谷P3850 书架
题目描述 Knuth先生家里有个精致的书架,书架上有N本书,如今他想学到更多的知识,于是又买来了M本不同的新书.现在他要把新买的书依次插入到书架中,他已经把每本书要插入的位置标记好了,并且相应的将它们 ...