java:观察者模式

java:观察者模式

1 前言

观察者模式,又被称为发布-订阅(Publish/Subscribe)模式,他定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态变化时,会通知所有的观察者对象,使他们能够自动更新自己。

2 使用

(2.1)结构

在观察者模式中有如下角色:

Subject:抽象主题(抽象被观察者),抽象主题角色把所有观察者对象保存在一个集合里,每个主题都可以有任意数量的观察者,抽象主题提供一个接口,可以增加和删除观察者对象。

ConcreteSubject:具体主题(具体被观察者),该角色将有关状态存入具体观察者对象,在具体主题的内部状态发生改变时,给所有注册过的观察者发送通知。

Observer:抽象观察者,是观察者的抽象类,它定义了一个更新接口,使得在得到主题更改通知时更新自己。

ConcreteObserver:具体观察者,实现抽象观察者定义的更新接口,以便在得到主题更改通知时更新自身的状态。

(2.2)案例

如公众号使用场景,当多个用户关注了某个公众号时,当公众号有内容更新时,会推送给关注了公众号的多个用户。这里,多个用户就是观察者,公众号就是被观察者。

下面以Java为例来实现一个简单的观察者模式:

在这里插入图片描述

Subject接口:

/**
 * 抽象主题角色类
 */
public interface Subject {

    // 添加订阅者(添加观察者对象)
    void attach(Observer observer);

    // 删除订阅者
    void detach(Observer observer);

    // 通知订阅者更新消息
    void notify(String message, String status);

}

SubscriptionSubject:

public class SubscriptionSubject implements Subject{

    List<Observer> users = new ArrayList<>();

    @Override
    public void attach(Observer observer) {
        users.add(observer);
    }

    @Override
    public void detach(Observer observer) {
        users.remove(observer);
    }

    @Override
    public void notify(String message, String status) {
        //  遍历集合
        for (Observer user : users) {
            //  调用观察者对象中的update方法
            user.update(message, status);
        }
    }
}

Observer:

/**
 * @author xiaoxu
 * @date 2024-04-20 19:43
 * learn_java:com.xiaoxu.design.observe.Observer
 * 抽象观察者类
 */
public interface Observer {

    void update(String message, String status);

}

AbstractObserver:

public abstract class AbstractObserver implements Observer{
    protected String status;

    public AbstractObserver(String status) {
        this.status = status;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}

ObserveUser:

public class ObserveUser extends AbstractObserver{

    private String name;

    public ObserveUser(String name, String status) {
        super(status);
        this.name = name;
    }

    @Override
    public void update(String message, String status) {
        System.out.println(String.format(
                "%s接收到消息:%s.原本状态为:%s," +
                        "更新后的状态为:%s.",
                this.name, message,
                this.getStatus(), status));
        this.setStatus(status);
    }
}

Client(验证上述的效果):

public class Client {

    public static void main(String[] args) {
        // 创建公众号对象
        SubscriptionSubject subject = new SubscriptionSubject();

        //  创建订阅者,订阅公众号
        subject.attach(new ObserveUser("小徐", "online"));
        subject.attach(new ObserveUser("小李", "offline"));

        //  公众号更新,发出消息给订阅者(观察者对象)
        subject.notify("来看心世界", "receive");
    }

}

执行结果如下:

小徐接收到消息:来看心世界.原本状态为:online,更新后的状态为:receive.
小李接收到消息:来看心世界.原本状态为:offline,更新后的状态为:receive.

(2.3)优缺点

优点:

(1)降低了目标与观察者之间的耦合关系,两者之间是抽象耦合关系。

(2)被观察者发送通知,所有注册的观察者都会收到信息【可以实现广播机制】。

缺点:

(1)如果观察者非常多的话,那么所有的观察者收到被观察者发送的通知会耗时。

(2)如果被观察者有循环依赖的话,那么被观察者发送通知会使观察者循环调用,会导致系统崩溃。

(2.4)使用场景

(1)对象间存在一对多关系,一个对象的状态发生改变会影响其他对象。

(2)当一个抽象模型有两个方面,其中一个方面依赖于另一方面时。

(2.5)JDK中提供的实现

在Java中,通过java.util.Observable类和java.util.Observer接口定义了观察者模式,只要实现它们的子类就可以编写观察者模式实例。

(1)Observable类

Observable类是抽象目标类(被观察者),它有一个Vector集合成员变量,用于保存所有要通知的观察者对象,下面来介绍它最重要的3个方法:

public synchronized void addObserver(Observer o)方法:用于将新的观察者对象添加到集合中。

public void notifyObservers(Object arg)方法:调用集合中的所有观察者对象的update方法,通知它们数据放生改变。通常越晚加入集合的观察者越先得到通知(因为JDK源码是索引从大到小遍历集合中的观察者)。

protected synchronized void setChanged()方法:用来设置一个boolean类型的内部标志,注明目标对象发生了变化。当它为true时,public void notifyObservers(Object arg)才会通知观察者。

JDK的完整Observable类实现如下:

package java.util;

public class Observable {
    private boolean changed = false;
    private Vector<Observer> obs;

    /** Construct an Observable with zero Observers. */

    public Observable() {
        obs = new Vector<>();
    }

    /**
     * Adds an observer to the set of observers for this object, provided
     * that it is not the same as some observer already in the set.
     * The order in which notifications will be delivered to multiple
     * observers is not specified. See the class comment.
     *
     * @param   o   an observer to be added.
     * @throws NullPointerException   if the parameter o is null.
     */
    public synchronized void addObserver(Observer o) {
        if (o == null)
            throw new NullPointerException();
        if (!obs.contains(o)) {
            obs.addElement(o);
        }
    }

    /**
     * Deletes an observer from the set of observers of this object.
     * Passing <CODE>null</CODE> to this method will have no effect.
     * @param   o   the observer to be deleted.
     */
    public synchronized void deleteObserver(Observer o) {
        obs.removeElement(o);
    }

    /**
     * If this object has changed, as indicated by the
     * <code>hasChanged</code> method, then notify all of its observers
     * and then call the <code>clearChanged</code> method to
     * indicate that this object has no longer changed.
     * <p>
     * Each observer has its <code>update</code> method called with two
     * arguments: this observable object and <code>null</code>. In other
     * words, this method is equivalent to:
     * <blockquote><tt>
     * notifyObservers(null)</tt></blockquote>
     *
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#hasChanged()
     * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)
     */
    public void notifyObservers() {
        notifyObservers(null);
    }

    /**
     * If this object has changed, as indicated by the
     * <code>hasChanged</code> method, then notify all of its observers
     * and then call the <code>clearChanged</code> method to indicate
     * that this object has no longer changed.
     * <p>
     * Each observer has its <code>update</code> method called with two
     * arguments: this observable object and the <code>arg</code> argument.
     *
     * @param   arg   any object.
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#hasChanged()
     * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)
     */
    public void notifyObservers(Object arg) {
        /*
         * a temporary array buffer, used as a snapshot of the state of
         * current Observers.
         */
        Object[] arrLocal;

        synchronized (this) {
            /* We don't want the Observer doing callbacks into
             * arbitrary code while holding its own Monitor.
             * The code where we extract each Observable from
             * the Vector and store the state of the Observer
             * needs synchronization, but notifying observers
             * does not (should not).  The worst result of any
             * potential race-condition here is that:
             * 1) a newly-added Observer will miss a
             *   notification in progress
             * 2) a recently unregistered Observer will be
             *   wrongly notified when it doesn't care
             */
            if (!changed)
                return;
            arrLocal = obs.toArray();
            clearChanged();
        }

        for (int i = arrLocal.length-1; i>=0; i--)
            ((Observer)arrLocal[i]).update(this, arg);
    }

    /**
     * Clears the observer list so that this object no longer has any observers.
     */
    public synchronized void deleteObservers() {
        obs.removeAllElements();
    }

    /**
     * Marks this <tt>Observable</tt> object as having been changed; the
     * <tt>hasChanged</tt> method will now return <tt>true</tt>.
     */
    protected synchronized void setChanged() {
        changed = true;
    }

    /**
     * Indicates that this object has no longer changed, or that it has
     * already notified all of its observers of its most recent change,
     * so that the <tt>hasChanged</tt> method will now return <tt>false</tt>.
     * This method is called automatically by the
     * <code>notifyObservers</code> methods.
     *
     * @see     java.util.Observable#notifyObservers()
     * @see     java.util.Observable#notifyObservers(java.lang.Object)
     */
    protected synchronized void clearChanged() {
        changed = false;
    }

    /**
     * Tests if this object has changed.
     *
     * @return  <code>true</code> if and only if the <code>setChanged</code>
     *          method has been called more recently than the
     *          <code>clearChanged</code> method on this object;
     *          <code>false</code> otherwise.
     * @see     java.util.Observable#clearChanged()
     * @see     java.util.Observable#setChanged()
     */
    public synchronized boolean hasChanged() {
        return changed;
    }

    /**
     * Returns the number of observers of this <tt>Observable</tt> object.
     *
     * @return  the number of observers of this object.
     */
    public synchronized int countObservers() {
        return obs.size();
    }
}

(2)Observer接口

Observer接口是抽象观察者,它监视目标对象的变化,当目标对象发生变化时,观察者得到通知,并调用update方法,进行相应的工作。

JDK中Observer接口如下所示:

public interface Observer {
    /**
     * This method is called whenever the observed object is changed. An
     * application calls an <tt>Observable</tt> object's
     * <code>notifyObservers</code> method to have all the object's
     * observers notified of the change.
     *
     * @param   o     the observable object.
     * @param   arg   an argument passed to the <code>notifyObservers</code>
     *                 method.
     */
    void update(Observable o, Object arg);
}

举个栗子,警察抓小偷:

警察抓小偷可以使用观察者模式来实现,警察是观察者,小偷是被观察者,代码如下:

小偷是一个被观察者,所以需要继承Observable类:

public class Thief extends Observable {
    private String name;

    public Thief(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void steal() {
        System.out.println("小偷" + this.name
                + ": 我偷了隔壁的珍珠奶茶," +
                "有没有人来抓我。");
        super.setChanged();     // changed = true
        super.notifyObservers();
    }
}

警察是一个观察者,所以需要让其实现Observer接口:

public class Policemen implements Observer {

    private String name;

    public Policemen(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void update(Observable o, Object arg) {
        System.out.println("小偷传的arg是null" +
                "(notifyObservers方法的arg参数):" + arg);
        System.out.println("警察" + this.name + ":"
                + ((Thief) o).getName() +
                ", 站住,你已经被包围了!双脚抱头,倒立站好!");
    }
}

Client调用:

public class TPClient {

    public static void main(String[] args) {
        //  创建小偷对象
        Thief t = new Thief("采花大盗");
        //  创建警察对象
        Policemen policemen = new Policemen("小徐");
        // 让警察盯着小偷(为小偷添加观察者)
        t.addObserver(policemen);
        //  小偷偷东西(被观察者发布事件,会被观察者发现)
        t.steal();
    }

}

执行结果如下:

小偷采花大盗: 我偷了隔壁的珍珠奶茶,有没有人来抓我。
小偷传的arg是null(notifyObservers方法的arg参数):null
警察小徐:采花大盗, 站住,你已经被包围了!双脚抱头,倒立站好!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/568462.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Visual Studio2022中使用水晶报表

1.创建水晶报表项目 选择需要的表 自动生成连接 选项&#xff1a;可跳过 后续还有一些 都能跳过 看你自己的需求 自己选的样式 自动生成 查看你的数据源&#xff0c;在选择数据集时已经有啦 不懂得可以看上集 字段可以直接拖&#xff0c;页面上的都是初始化选过的 点击生成 成功…

【系统架构师】-选择题(一)

1、信息系统规划方法中&#xff0c;关键成功因素法通过对关键成功因素的识别&#xff0c;找出实现目标所需要的关键信息集合&#xff0c;从而确定系统开发的 &#xff08;优先次序&#xff09; 。关键成功因素来源于组织的目标&#xff0c;通过组织的目标分解和关键成功因素识别…

docker容器内彻底移除iptables服务的实现方法

背景 我创建的容器使用的是centos6的标准镜像&#xff0c;所以内置了iptables服务。容器启动后iptables服务默认就启动了。iptables设置的规则默认是所有流量都无法通行。而对于服务器的管理使用的是宿主机的防火墙。这样就导致在实现用iptables动态给容器添加端口映射时不成功…

关于C++STL的总结(基础使用和底层原理)

STL是什么&#xff1f; STL即&#xff08;Standard Template Library&#xff09;标准模板库&#xff0c;提供了常见的数据结构和算法函数等&#xff0c;其下共包含六大组件&#xff1a; 容器算法迭代器仿函数适配器空间配置器 本篇重点介绍容器的使用和简单的底层实现原理&…

推荐六款图片编辑软件

图片编辑、抠图、拼图、压缩、放大、加字体、转格式等各种功能应有尽有&#xff0c;收藏这一篇就够了&#xff01; 综合编辑&#xff1a;图片编辑助手 这是一款电脑软件&#xff0c;里面有超多图片处理功能&#xff0c;压缩图片到指定大小、消除任意位置的图片水印、按指定大小…

【C++】---STL之vector的模拟实现

【C】---STL之vector的模拟实现 一、vector在源码中的结构&#xff1a;二、vector类的实现&#xff1a;1、vector的构造2、析构3、拷贝构造4、赋值运算符重载5、迭代器6、operator[ ]7、size()8、capacity()9、reserve()10、resize()11、empty()12、push_back()13、pop_back()1…

如何在PostgreSQL中设置自动清理过期数据的策略

文章目录 方法一&#xff1a;使用临时表和定期清理步骤&#xff1a;示例代码&#xff1a;创建临时表&#xff1a;定期清理脚本&#xff08;bash psql&#xff09;&#xff1a; 方法二&#xff1a;使用分区表和定期清理步骤&#xff1a;示例代码&#xff1a;创建分区表&#xf…

《内向者优势》:不要低估一个内向的人

#世界读书日 作者主页&#xff1a; &#x1f517;进朱者赤的博客 精选专栏&#xff1a;&#x1f517;经典算法 作者简介&#xff1a;阿里非典型程序员一枚 &#xff0c;记录在大厂的打怪升级之路。 一起学习Java、大数据、数据结构算法&#xff08;公众号同名&#xff09; ❤…

Redis篇:缓存更新策略最佳实践

前景&#xff1a; 缓存更新是redis为了节约内存而设计出来的一个东西&#xff0c;主要是因为内存数据宝贵&#xff0c;当我们向redis插入太多数据&#xff0c;此时就可能会导致缓存中的数据过多&#xff0c;所以redis会对部分数据进行更新&#xff0c;或者把他叫为淘汰更合适&a…

Vue3的监听属性watch和计算属性computed

监听属性watch 计算属性computed 一、监听属性watch watch 的第一个参数可以是不同形式的“数据源&#xff0c;watch 可以监听以下几种数据&#xff1a; 一个 ref (包括计算属性)、 一个响应式对象、 一个 getter 函数、 或多个数据源组成的数组 watch 的参数:监视的回调&…

代码随想录算法训练营第三十五天|860.柠檬水找零、406.根据身高重建队列、452. 用最少数量的箭引爆气球

860. 柠檬水找零 思路&#xff1a; 只需要维护三种金额的数量&#xff0c;5&#xff0c;10和20。 有如下三种情况&#xff1a; 情况一&#xff1a;账单是5&#xff0c;直接收下。情况二&#xff1a;账单是10&#xff0c;消耗一个5&#xff0c;增加一个10情况三&#xff1a;…

好友关注-实现分页查询收邮箱

9.5好友关注-实现分页查询收邮箱 需求&#xff1a;在个人主页的“关注”卡片中&#xff0c;查询并展示推送的Blog信息&#xff1a; 具体操作如下&#xff1a; 1、每次查询完成后&#xff0c;我们要分析出查询出数据的最小时间戳&#xff0c;这个值会作为下一次查询的条件 2…

考研党打印资料怎么使用云打印服务?

对于准备考研的同学们来说&#xff0c;在备考的时候需要准备许多资料&#xff0c;这些资料的打印费用成为了考研党的巨额支出。那么在生活费有限的情况下&#xff0c;考研党打印资料最好是选择云打印服务&#xff0c;因为易绘创云打印服务低至5分钱/页还包邮。那么考研党打印资…

Pytest精通指南(28)钩子函数-测试报告(pytest-html)

文章目录 前言应用场景插件安装参数分析使用方法拓展-定制化报告 前言 在软件开发过程中&#xff0c;测试是确保代码质量的关键环节。 而测试报告则是测试过程中不可或缺的输出物&#xff0c;它为我们提供了关于测试用例执行情况的详细信息&#xff0c;帮助我们快速定位和解决问…

服务器(AIX、Linux、UNIX)性能监视器工具【nmon】使用介绍

目录 ■nmon简介 1.安装 2.使用简介 3.使用&#xff08;具体使用的例子【CPU】【内存】&#xff09; 4.采集数据 5.查看log&#xff08;根据结果&#xff0c;生成报表&#xff09; 6.分析结果 ■nmon简介 nmon&#xff08;"Nigels performance Monitor"&…

比特币成长的代价

作者&#xff1a;Jeffrey Tucker&#xff0c;作家和总裁。曾就经济、技术、社会哲学和文化等话题广泛发表演讲。编译&#xff1a;秦晋 2017 年之后参与比特币市场的人遇到了与之前的人不同的操作和理想。如今&#xff0c;没有人会太在意之前的事情&#xff0c;说的是 2010-2016…

SL3038 耐压150V恒压芯片 60V降24V 72V降12V降压IC

SL3038 是一款恒压芯片&#xff0c;其耐压值为 150V。这意味着它可以在高达 150V 的电压下工作而不会损坏。现在&#xff0c;让我们来讨论您提到的两个降压应用&#xff1a;从 60V 降到 24V 和从 72V 降到 12V。 1. 60V 降到 24V&#xff1a; 输入电压&#xff1a;60V 输出电…

02 IO口的操作

文章目录 前言一、IO的概念1.IO接口2.IO端口 二、CPU和外设进行数据传输的方法1.程序控制方式1.1 无条件1.2 查询方式 2.中断方式3.DMA方式 一、方法介绍和代码编写1.前置知识2.程序方式1.1 无条件方式1.1.1 打开对应的GPIO口1.1.2 初始化对应的GPIO引脚1.1.2.1 推挽输出1.1.2.…

【Hadoop】-Hive部署[12]

目录 思考 VMware虚拟机部署 规划 步骤1&#xff1a;安装MySQL数据库 步骤2&#xff1a;配置Hadoop 步骤3&#xff1a;下载解压Hive 步骤4&#xff1a;提供MySQL Driver包 步骤5&#xff1a;配置Hive 步骤6&#xff1a;初始化元数据库 步骤7&#xff1a;启动Hive&…

TDSQL同一个所属Set显示3个备份节点

欢迎关注“数据库运维之道”公众号&#xff0c;一起学习数据库技术! 本期将为大家分享《TDSQL同一个所属Set显示3个备份节点》的处置案例。 关键词&#xff1a;分布式数据库、TDSQL、备份节点 1、问题描述 登录赤兔管理平台&#xff0c;单击左侧导航栏“实例管理/集群管理”…
最新文章