java:观察者模式

embedded/2024/9/22 23:58:28/

java_0">java观察者模式

1 前言

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

2 使用

(2.1)结构

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

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

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

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

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

(2.2)案例

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

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

在这里插入图片描述

Subject接口:

java">/*** 抽象主题角色类*/
public interface Subject {// 添加订阅者(添加观察者对象)void attach(Observer observer);// 删除订阅者void detach(Observer observer);// 通知订阅者更新消息void notify(String message, String status);}

SubscriptionSubject:

java">public class SubscriptionSubject implements Subject{List<Observer> users = new ArrayList<>();@Overridepublic void attach(Observer observer) {users.add(observer);}@Overridepublic void detach(Observer observer) {users.remove(observer);}@Overridepublic void notify(String message, String status) {//  遍历集合for (Observer user : users) {//  调用观察者对象中的update方法user.update(message, status);}}
}

Observer:

java">/*** @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:

java">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:

java">public class ObserveUser extends AbstractObserver{private String name;public ObserveUser(String name, String status) {super(status);this.name = name;}@Overridepublic 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(验证上述的效果):

java">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");}}

执行结果如下:

java">小徐接收到消息:来看心世界.原本状态为: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类实现如下:

java">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接口如下所示:

java">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类:

java">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 = truesuper.notifyObservers();}
}

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

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

Client调用:

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

执行结果如下:

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

http://www.ppmy.cn/embedded/20395.html

相关文章

企业智能名片小程序:AI智能跟进功能助力精准营销新篇章

在数字化浪潮的推动下&#xff0c;企业营销手段不断迭代升级。如今&#xff0c;一款集手机号授权自动获取、智能提醒、访客AI智能跟进及客户画像与行为记录于一体的企业智能名片小程序&#xff0c;正以其强大的AI智能跟进功能&#xff0c;助力企业开启精准营销的新篇章。 通过深…

JAVA 中间件之 Mycat2

Mycat2应用与实战教程 1.Mycat2概述 1.1 什么是MyCat 官网&#xff1a; http://mycatone.top/ Mycat 是基于 java 语言编写的数据库中间件&#xff0c;是一个实现了 MySQL 协议的服务器&#xff0c;前端用户可以把它看作是一个数据库代理&#xff0c;用 MySQL 客户端工具和…

D-Wave 推出快速退火功能,扩大量子计算性能增益

内容来源&#xff1a;量子前哨&#xff08;ID&#xff1a;Qforepost&#xff09; 文丨浪味仙 排版丨沛贤 深度好文&#xff1a;1400字丨6分钟阅读 摘要&#xff1a;量子计算公司 D-Wave 宣布在其 Leap™ 实时量子云服务中的所有量子处理单元 (QPU) 上推出新的快速退火功能。…

Kafka 3.x.x 入门到精通(08)——对标尚硅谷Kafka教程

Kafka 3.x.x 入门到精通&#xff08;08&#xff09;——对标尚硅谷Kafka教程 5. Kafka优化5.1 资源配置5.1.1 操作系统5.1.2 磁盘选择5.1.3 网络带宽5.1.4 内存配置5.1.5 CPU选择 5.2 集群容错5.2.1 副本分配策略5.2.2 故障转移方案5.2.3 数据备份与恢复 5.3 参数配置优化5.4 数…

leetcode 每日一题目 (树的直径 +DFS的深刻理解)

如下是题目的简单描述&#xff1a; 给你一棵二叉树的根节点 root &#xff0c;二叉树中节点的值 互不相同 。另给你一个整数 start 。在第 0 分钟&#xff0c;感染 将会从值为 start 的节点开始爆发。 每分钟&#xff0c;如果节点满足以下全部条件&#xff0c;就会被感染&…

刷机维修进阶教程---开机定屏 红字感叹号报错 写字库保资料 救砖 刷官方包保资料的步骤方法解析

在维修各种机型 中经常会遇到开机定屏 进不去系统,正常使用无故定屏进不去系统或者更新降级开机红色感叹号的一些故障机。但顾客需要报资料救砖的要求,遇到这种情况。我们首先要确定故障机型的缘由。是摔 还是更新降级 还是无故使用重启定屏等等。根据原因来对症解决。 通过…

Linux centos stream9 htop

Linux中,top动态查看进程。而htop是top的增强版本,功能更加强大,操作也更方便。 一、htop功能 htop命令是一个Linux实用程序,用于显示有关系统进程的关键信息。它可以被看作是Windows任务管理器的Linux版本。htop更像是一个交互式程序,因为它支持鼠标和键盘操作来在值和…

【UnityRPG游戏制作】RPG项目的背包系统商城系统和BOSS大界面

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;Uni…