被观察者的接口类

import java.util.Observer;
/*** 气温预报(观察者模式)* @author Administrator*被观察者接口即subject目标接口气温*/
public interface Temperature{//增加观察者public void addObs(Observer o);//删除观察者public void deleteObs(Observer o);//通知观察者public void notifyObs(int t);
}

被观察者实现类

/*** 具体主题被观察者* @author Administrator**/
public class TemperatureImpl extends Observable implements Temperature {@Overridepublic synchronized void addObserver(Observer o) {super.addObserver(o);}@Overridepublic synchronized void deleteObserver(Observer o) {super.deleteObserver(o);}@Overridepublic void notifyObservers(Object arg) {super.setChanged();super.notifyObservers(arg);}
/*** 当具体被观察者类集成Observable时这些其实时不需要的,因为在Observable类中其实已经有定义,* 上面的重写这些方法已经足够(也可不重写直接调用父类的方法)* 如果采用下面的方法就相当于自己实现观察者模式,不用api中提供的类* 必须加上相应的Vector obs观察者数组用于存放观察者列表*/@Overridepublic void addObs(Observer o) {}@Overridepublic void deleteObs(Observer o) {}@Overridepublic void notifyObs(int t) {}}

观察者接口类

import java.util.Observer;/*** 气温显示(根据气温的实时变化来实时显示)* @author Administrator**/
public interface TemperatureShow extends Observer {}

观察者实现类

import java.util.Observable;public class TemperatureShowImpl implements TemperatureShow {
public String tname;public String getTname() {return tname;
}public void setTname(String tname) {this.tname = tname;
}@Overridepublic void update(Observable o, Object arg) {System.out.println(tname+":"+arg);}}

测试类

public class TestMain{
public static double i=0;
public static void main(String[] args) {//创建被观察者TemperatureImpl t = new TemperatureImpl();//创建观察者1TemperatureShowImpl s = new TemperatureShowImpl();s.setTname("高温预报");t.addObserver(s);//创建观察者2TemperatureShowImpl s1 = new TemperatureShowImpl();s1.setTname("低温预报");t.addObserver(s1);t.notifyObservers(Math.random());}
}

这里附上Observable类

/** @(#)Observable.java 1.39 05/11/17** Copyright 2006 Sun Microsystems, Inc. All rights reserved.* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.*/package java.util;/*** This class represents an observable object, or "data"* in the model-view paradigm. It can be subclassed to represent an * object that the application wants to have observed. * <p>* An observable object can have one or more observers. An observer * may be any object that implements interface <tt>Observer</tt>. After an * observable instance changes, an application calling the * <code>Observable</code>'s <code>notifyObservers</code> method  * causes all of its observers to be notified of the change by a call * to their <code>update</code> method. * <p>* The order in which notifications will be delivered is unspecified.  * The default implementation provided in the Observable class will* notify Observers in the order in which they registered interest, but * subclasses may change this order, use no guaranteed order, deliver * notifications on separate threads, or may guarantee that their* subclass follows this order, as they choose.* <p>* Note that this notification mechanism is has nothing to do with threads * and is completely separate from the <tt>wait</tt> and <tt>notify</tt> * mechanism of class <tt>Object</tt>.* <p>* When an observable object is newly created, its set of observers is * empty. Two observers are considered the same if and only if the * <tt>equals</tt> method returns true for them.** @author  Chris Warth* @version 1.39, 11/17/05* @see     java.util.Observable#notifyObservers()* @see     java.util.Observable#notifyObservers(java.lang.Object)* @see     java.util.Observer* @see     java.util.Observer#update(java.util.Observable, java.lang.Object)* @since   JDK1.0*/
public class Observable {private boolean changed = false;private Vector 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();}
}

Java观察者模式例子相关推荐

  1. java 观察者模式示例_观察者设计模式示例

    java 观察者模式示例 本文是我们名为" Java设计模式 "的学院课程的一部分. 在本课程中,您将深入研究大量的设计模式,并了解如何在Java中实现和利用它们. 您将了解模式如 ...

  2. jsch连接mysql_求用jsch网络工具包通过ssh连接远程oracle数据库并发送sql操作语句(数据库在unix上)java代码例子...

    求用jsch网络工具包通过ssh连接远程oracle数据库(数据库在unix上)java代码例子:为何jsch发送:sqlplususer/pwd@service此命令,却没有结果返回啊.下面是代码: ...

  3. java 观察者模式示例_Java中的观察者设计模式-示例教程

    java 观察者模式示例 观察者模式是行为设计模式之一 . 当您对对象的状态感兴趣并希望在发生任何更改时得到通知时,观察者设计模式很有用. 在观察者模式中,监视另一个对象状态的对象称为Observer ...

  4. java观察者模式本质_6.[研磨设计模式笔记]观察者模式

    1.定义 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动更新. 2.解决问题 --订阅报纸 看起来订阅者是直接根有据打交道,但实际上,订阅者的订阅数据 ...

  5. arcengine java_浅析 ArcEngine Java - EngineViewer 例子

    例子源文件:\DeveloperKit\samples\Applications\EngineViewer\Java\EngineViewer.jar 运行环境的搭建: 解压后,在Eclipse或Jb ...

  6. [Java]观察者模式和中介者模式改造机场

    [Java]观察者模式和中介者模式改造机场 文章目录 [Java]观察者模式和中介者模式改造机场 题目 代码部分 运行结果 补充 题目 请以下面的情景为基础,将以下的情景进行 优化: 1. 定义4个处 ...

  7. Java观察者模式理解和实现

    今天本想一本正经的把RxJava看一看,想着前段时间RxJava都已经到了第二版,而自己RxJava的认识还只是很基础,甚至连基础都算不上,所以本着以后能在项目里优雅地把他用出来的想法,我开始了RxJ ...

  8. 一个基于RSA算法的Java数字签名例子

    ====================================================== 注:本文源代码点此下载 ================================= ...

  9. Java 观察者模式介绍及示例

    Java 观察者模式介绍及示例 一.观察者模式简介 1.1概念 观察者模式(Observer Pattern) : 观察者模式又名 发布/订阅模式,属于行为模式,定义了对象中一对多的依赖关系,让多个观 ...

  10. 观察者模式及Java实现例子

    观察者模式 观察者模式 Observer 观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象. 这个主题对象在状态上发生变化时,会通知所有观察者对象,让它们能够自动更新自己. ...

最新文章

  1. python 计时器 timeit repeat 计算(语句)(函数)耗时 时间 运行时长
  2. mysql数据库new和old_数据库触发器中new表和old表是什么意思?
  3. PHP str_replace() 和str_ireplace()函数
  4. window下的SCROLLbar的使用技巧
  5. 我的Maven POM配置
  6. Atitit diy战略 attilax总结
  7. python 编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址_[LeetCode] 468. 验证IP地址
  8. 最新爱客影院自动采集源码v3.5.5
  9. 通达信服务器在哪个文件里,通达信“指标模块”存放在哪个文件夹里
  10. kali linux 初始密码
  11. etc的常见算法_UI图集压缩优化,以及对Dither和ETC1算法的深入了解
  12. 关于学习管理系统 LMS
  13. windows通过浏览器远程连接Linux服务器的jupyter
  14. 【Codeforces Round #614(div2)】E-Xenon's Attack on the Gangs(树形dp)
  15. 2月综艺节目网络关注度榜出炉 《王牌对王牌》跃居榜首
  16. 计算机编写代码简介,Vcomputer简介
  17. Spring Boot集成Mybatis-Plus多租户架构实战
  18. 第三届上海市青少年算法竞赛题解
  19. 2022-2028年中国铁合金市场投资分析及前景预测报告
  20. Error while executing topic command:KeeperErrorCode=NoNode for /brokers/ids

热门文章

  1. addr2line命令使用
  2. java考试题及答案翁凯,快来收藏!
  3. OPENSTACK超售比例之VCPU
  4. 陶哲轩教你学数学 第1章 解题策略 读书笔记
  5. matlab初学者_脚本文件调用函数文件
  6. 京东超市 导航条布局
  7. 计算机控制系统信号的采样,计算机控制系统-信号采样与分析演示.ppt
  8. 如何在matlab坐标轴上输入希腊字符和开根号符号
  9. 毕业论文系列-公式编号-等号对齐及编号
  10. 刚入职就写了个bug,把几万用户搞蓝屏了···