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源码分析)的更多相关文章

  1. JDK Collection 源码分析(2)—— List

    JDK List源码分析 List接口定义了有序集合(序列).在Collection的基础上,增加了可以通过下标索引访问,以及线性查找等功能. 整体类结构 1.AbstractList   该类作为L ...

  2. JDK AtomicInteger 源码分析

    @(JDK)[AtomicInteger] JDK AtomicInteger 源码分析 Unsafe 实例化 Unsafe在创建实例的时候,不能仅仅通过new Unsafe()或者Unsafe.ge ...

  3. 第十篇:Spark SQL 源码分析之 In-Memory Columnar Storage源码分析之 query

    /** Spark SQL源码分析系列文章*/ 前面讲到了Spark SQL In-Memory Columnar Storage的存储结构是基于列存储的. 那么基于以上存储结构,我们查询cache在 ...

  4. 十、Spring之BeanFactory源码分析(二)

    Spring之BeanFactory源码分析(二) 前言 在前面我们简单的分析了BeanFactory的结构,ListableBeanFactory,HierarchicalBeanFactory,A ...

  5. 【十八】php文件下载源码

    index.php <!DOCTYPE html> <html> <head> <title></title> <meta chars ...

  6. JDK Collection 源码分析(1)—— Collection

    JDK Collection   JDK Collection作为一个最顶层的接口(root interface),JDK并不提供该接口的直接实现,而是通过更加具体的子接口(sub interface ...

  7. JDK Collection 源码分析(3)—— Queue

    @(JDK)[Queue] JDK Queue Queue:队列接口,对于数据的存取,提供了两种方式,一种失败会抛出异常,另一种则返回null或者false.   抛出异常的接口:add,remove ...

  8. Netty源码分析 (八)----- write过程 源码分析

    上一篇文章主要讲了netty的read过程,本文主要分析一下write和writeAndFlush. 主要内容 本文分以下几个部分阐述一个java对象最后是如何转变成字节流,写到socket缓冲区中去 ...

  9. ABP源码分析一:整体项目结构及目录

    ABP是一套非常优秀的web应用程序架构,适合用来搭建集中式架构的web应用程序. 整个Abp的Infrastructure是以Abp这个package为核心模块(core)+15个模块(module ...

随机推荐

  1. 容器编排系统K8s之Prometheus监控系统+Grafana部署

    前文我们聊到了k8s的apiservice资源结合自定义apiserver扩展原生apiserver功能的相关话题,回顾请参考:https://www.cnblogs.com/qiuhom-1874/ ...

  2. kali中安装漏洞靶场Vulhub

    一.什么是vulhub? Vulhub是一个基于docker和docker-compose的漏洞环境集合,进入对应目录并执行一条语句即可启动一个全新的漏洞环境,让漏洞复现变得更加简单,让安全研究者更加 ...

  3. 【Git】2、Linux快速安装Git环境 & oh-my-zsh

    Linux快速安装Git环境 文章目录 Linux快速安装Git环境 1.Linux安装Git 2.安装zsh 3.安装oh-my-zsh 3.1.安装oh-my-zsh 3.2. 测试验证 4.小结 ...

  4. show engine innodb status

    TRANSACTIONS------------Trx id counter 2003909(当前事务号)Purge done for trx's n:o < 2003905 (清理线程完成到了 ...

  5. 深度解读设备的“万能语言”HarmonyOS的分布式软总线能力

    摘要:本文分享鸿蒙分布式软总线,并对相关源代码进行解析,为在鸿蒙系统平台上工作的相关人员的信息参考和指导. 总线是一种内部结构,在计算机系统中,主机的各个部件通过总线相连,外部设备通过相应的接口电路再 ...

  6. 同一份数据,Redis为什么要存两次

    前言 在 Redis 中,有一种数据类型,当在存储的时候会同时采用两种数据结构来进行分别存储,那么 Redis 为什么要这么做呢?这么做会造成同一份数据占用两倍空间吗? 五种基本类型之集合对象 Red ...

  7. uni-app开发经验分享七: 有关列表数据下拉加载方法的解析及记录

    在使用uni.request获取后台数据时,我们往往碰到一个问题,列表的懒加载及数据实时更新,这里记录下我制作这类功能的方法. 问题描述:后台返回数据,前端需要进行10个为一组来分页,先显示前10个, ...

  8. [微信小程序]字体文件,字体图标(.ttf,.woff,woff2)等无法显示问题

    一. 背景 项目引用了第三方UI框架Vant-weapp,但是前几天Vant的cdn被运营商封禁,导致van-icon无法使用. 有赞官方在Github上给出了在小程序app.wxss上添加以下代码的 ...

  9. nfs samba文件共享服务

    (注意:实验之前强关闭selinux和防火墙) 一丶nfs ① 1.服务端 启动服务 systemctl start nfs.service   配置文件 vim /etc/exports share ...

  10. VS2019中scanf返回值被忽略的问题及其解决方法

    目录 [问题](#昨天在使用Visual Studio 2019编写C语言程序时遇到了scanf返回值被忽略问题) 问题原因 方法① 方法② 方法③ 方法④ 昨天在使用Visual Studio 20 ...