Day55-设计模式-观察者模式


title: Day55-设计模式-观察者模式
date: 2021-03-26 15:46:29
author: Liu_zimo


设计模式

  • 设计模式分为三种类型,共23种
    1. 创建型模式:单例模式、抽象工厂模式、原型模式、建造者模式、工厂模式
    2. 结构型模式:适配器模式、桥接模式、装饰模式、组合模式、外观模式、享元模式、代理模式
    3. 行为型模式:模版方法模式、命令模式、访问者模式、迭代器模式、观察者模式、中介者模式、备忘录模式、解释器模式(Interpreter模式)、状态模式、策略模式、职责链模式(责任链模式)。

观察者模式

  • 天气预报项目需求

    1. 气象站可以将每天测量到的温度,湿度,气压等等以公告的形式发布出去(比如发布到自己的网站或第三方)
    2. 需要设计开放型API,便于其他第三方也能接入气象站获取数据
    3. 提供温度、气压和湿度的接口
    4. 测量数据更新时,要能实时的通知给第三方
  • 普通方案

    • 通过对气象站项目的分析,我们可以初步设计出一个WeatherData类
    1. 通过getXxx方法,可以让第三方接入,并得到相关信息
    2. 当数据有更新时,气象站通过调用dataChange()去更新数据,当第三方再次获取时,就能得到最新数据,当然也可以推送。
    • 问题分析:
      1. 其他第三方接入气象站获取数据的问题
      2. 无法在运行时动态的添加第三方(新浪网站)
      3. 违反ocp原则 => 观察者模式
    • 在WeatherData中,当增加一个第三方,都需要创建一个对应的第三方的公告板对象,并加入到dataChange,不利于维护,也不是动态加入
package com.zimo.设计模式.行为型模式.观察者模式.普通方案;
/**
 * 设计模式 - 观察者模式:天气预报案例 - 普通方案
 *      当前气象情况
 * @author Liu_zimo
 * @version v0.1 by 2021/3/26 16:37
 */
public class CurrentConditions {
    private float temperature;  // 温度
    private float pressure;     // 气压
    private float humidity;     // 湿度
    // 由WeatherData调用,推送模式
    public void update(float temperature, float pressure, float humidity){
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        this.display();
    }
    public void display(){
        System.out.println("--- today mT:" + this.temperature + "---");
        System.out.println("--- today mP:" + this.pressure + "---");
        System.out.println("--- today mH:" + this.humidity + "---");
    }
}
----------------------------------------------------------------------------
package com.zimo.设计模式.行为型模式.观察者模式.普通方案1;
/**
 * 设计模式 - 观察者模式:天气预报案例 - 普通方案
 *      气象数据类 - 核心类
 *      1.包含最新的天气情况  2.含有CurrentConditions对象
 *      3.当数据有更新时,就主动的调用CurrentConditions对象update方法(含display),这样他们(接入方)就看到最新的信息
 * @author Liu_zimo
 * @version v0.1 by 2021/3/26 16:10
 */
public class WeatherData {
    private float temperature;  // 温度
    private float pressure;     // 气压
    private float humidity;     // 湿度
    private CurrentConditions currentConditions;
    public WeatherData(CurrentConditions currentConditions) { this.currentConditions = currentConditions; }
    public float getTemperature() { return temperature; }
    public float getPressure() { return pressure; }
    public float getHumidity() { return humidity; }
    public void dataChange(){ currentConditions.update(getTemperature(), getPressure(), getHumidity()); }
    // 当数据更新时,调用setData
    public void setData(float temperature, float pressure, float humidity){
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        // 将最新的信息推送给接入方
        dataChange();
    }
}
----------------------------------------------------------------------------
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);
}
观察者模式原理
  • 观察者模式类似订牛奶业务
    1. 牛奶站/气象局:Subject
    2. 用户/第三方网站:Observer
  • Subject:登记注册、移除和通知
    1. registerObserver 注册
    2. removeObserver 移除
    3. notifyObservers()通知所有的注册的用户,根据不同需求,可以是更新数据,让用户来取,也可能是实施推送,看具体需求定
  • Observer:接收输入
  • 观察者模式:对象之间多对一依赖的一种设计方案,被依赖的对象为Subject,依赖的对象为Observer,Subject通知Observer变化,比如这里的奶站是
    Subject,是1的一方。用户时Observer,是多的一方。

天气预报UML类图

package com.zimo.设计模式.行为型模式.观察者模式.天气预报;
/**
 * 设计模式 - 观察者模式:天气预报案例
 *      观察者接口
 * @author Liu_zimo
 * @version v0.1 by 2021/3/26 17:20
 */
public interface Observer {
    public void update(float temperature,float pressure, float humidity);
}
--------------------------------------------------------------------------
package com.zimo.设计模式.行为型模式.观察者模式.天气预报;
/**
 * 设计模式 - 观察者模式:天气预报案例
 *      气象站
 * @author Liu_zimo
 * @version v0.1 by 2021/3/26 17:17
 */
public interface Subject {
    public void registerObserver(Observer o);
    public void removeObserver(Observer o);
    public void notifyObservers();
}
--------------------------------------------------------------------------
package com.zimo.设计模式.行为型模式.观察者模式.天气预报;
import com.zimo.设计模式.行为型模式.观察者模式.普通方案.CurrentConditions;
import java.util.ArrayList;
/**
 * 设计模式 - 观察者模式:天气预报
 *      气象数据类 - 核心类
 *      1.包含最新的天气情况  2.含有观察者集合,使用ArrayList管理
 *      3.当数据有更新时,就主动的调用ArrayList,通知所有的(接入方)看到最新的信息
 * @author Liu_zimo
 * @version v0.1 by 2021/3/26 17:24
 */
public class WeatherData implements Subject{
    private float temperature;  // 温度
    private float pressure;     // 气压
    private float humidity;     // 湿度
    private ArrayList<Observer> observers;
    public WeatherData() { this.observers = new ArrayList<>(); }
    public void dataChange(){ notifyObservers(); }
    // 当数据更新时,调用setData
    public void setData(float temperature, float pressure, float humidity){
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        // 将最新的信息推送给接入方
        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 notifyObservers() {
        for (Observer observer : this.observers) {
            observer.update(this.temperature, this.pressure, this.humidity);
        }
    }
}
--------------------------------------------------------------------------
package com.zimo.设计模式.行为型模式.观察者模式.天气预报;
/**
 * 设计模式 - 观察者模式:天气预报
 *      当前气象情况
 * @author Liu_zimo
 * @version v0.1 by 2021/3/26 17:23
 */
public class CurrentConditions implements Observer{
    private float temperature;  // 温度
    private float pressure;     // 气压
    private float humidity;     // 湿度
    // 由WeatherData调用,推送模式
    public void update(float temperature, float pressure, float humidity){
        this.temperature = temperature;
        this.pressure = pressure;
        this.humidity = humidity;
        this.display();
    }
    public void display(){
        System.out.println("--- today mT:" + this.temperature + "---");
        System.out.println("--- today mP:" + this.pressure + "---");
        System.out.println("--- today mH:" + this.humidity + "---");
    }
}
--------------------------------------------------------------------------
package com.zimo.设计模式.行为型模式.观察者模式.天气预报;
/**
 * 设计模式 - 观察者模式:天气预报
 *      百度接入
 * @author Liu_zimo
 * @version v0.1 by 2021/3/26 17:37
 */
public class BaiduSite implements Observer{
    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;
        this.display();
    }
    public void display(){
        System.out.println("--- baidu mT:" + this.temperature + "---");
        System.out.println("--- baidu mP:" + this.pressure + "---");
        System.out.println("--- baidu mH:" + this.humidity + "---");
    }
}
--------------------------------------------------------------------------
public static void main(String[] args) {
    WeatherData weatherData = new WeatherData();
    CurrentConditions currentConditions = new CurrentConditions();
    BaiduSite baiduSite = new BaiduSite();
    weatherData.registerObserver(currentConditions);
    weatherData.registerObserver(baiduSite);
    weatherData.setData(10, 100, 30);
    weatherData.removeObserver(currentConditions);
    weatherData.setData(30, 200, 20);
}
  • 观察者模式的好处:
    1. 观察者模式设计后,会以集合的方式来管理用户(Observer),包括注册,移除和通知
    2. 这样,我们增加观察者(这里可以理解成一个新的公告板),就不需要去修改核心类WeatherData不会修改代码,遵守了ocp原则

JDK中应用源码分析

  • JDK的Observable类就使用了观察者模式
  • Observable的作用和地位 ===>>> Subject
  • Observable是类,不是接口,类中已经实现了核心的方法,即管理Observer的方法add… delete… notify…
  • Observer的作用和地位 ===>>> Observer,有update
  • Observable和 Observer的使用方法和前面讲过的一样,只是Observable是类,通过继承来说实现观察者模式
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柳子陌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值