import java.util.Observable;
import java.util.Observer;
/**
* 一个被观察者多个观察者
* @author zengst
* @date
*/
public class ObserverTest1 {
public static void main(String args[]){
BeingWatched bw = new BeingWatched();
Watch1 w1 = new Watch1();
Watch2 w2 = new Watch2();
//光标定位到某一行,crtl+Alt+向下箭头,复制当前行内容到下一行
bw.addObserver(w1);
bw.addObserver(w2);
bw.counter();
}
}
class Watch1 implements Observer{
//这里的args是被观察者调用notifyObservers方法时传递的参数
//这里的o是被观察者的父类,因为一个观察者可以观者多个被观察者
//所以这里无法直接通过o调用某一个被观察者定义的方法
@Override
public void update(Observable o, Object arg) {
System.out.println("我是观察者一,被观察的人变化了");
}
}
class Watch2 implements Observer{
//这里的args是被观察者调用notifyObservers方法时传递的参数
//这里的o是被观察者的父类,因为一个观察者可以观者多个被观察者
//所以这里无法直接通过o调用某一个被观察者定义的方法
@Override
public void update(Observable o, Object arg) {
System.out.println("我是观察者二,被观察的人变化了");
}
}
class BeingWatched extends Observable{
public int j =888;
public int cry(){
System.out.println("I am crying--"+j);
return j;
}
void counter(){
try{
for(int i=0; i<5;i++){
setChanged();
notifyObservers(i);
Thread.sleep(1000);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
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();
}
}
相关推荐
`Observable`类代表被观察的对象,它可以有多个观察者,而`Observer`接口则定义了观察者的通用行为。 ### `Observable`类 `Observable`类是被观察对象的基类,它维护了一个观察者列表。当`Observable`对象的状态...
2. **观察者类实现**:接着,定义一个观察者类实现`Observer`接口: ```java import java.util.Observable; import java.util.Observer; public class MyObserver implements Observer { @Override public ...
在Java中,`Observable`类代表被观察者,它可以被多个观察者订阅。这个类提供了一些方法来添加、移除和通知观察者。`Observer`接口定义了观察者的行为,每个实现该接口的类都必须实现`update`方法,这个方法会在被...
1. **`Observable`类**:代表被观察的对象,可以注册多个观察者,并在状态改变时通知它们。`Observable`类提供了`addObserver()`方法用于添加观察者,`setChanged()`方法标记状态已改变,以及`notifyObservers()`...
观察者模式是软件设计模式中的一种行为模式,它允许一个对象(称为被观察者)在状态发生改变时通知其他对象(称为观察者)。在Java中,观察者模式得到了内置支持,主要体现在`java.util.Observable`类和`java.util....
通常,这个Demo会包含一个可观察的对象(Observable)和多个观察者(Observer),当可观察对象的状态发生变化时,会触发通知机制,使得观察者接收到这一变化并作出相应的响应。 描述中提到,这个Demo将使用Java自带...
主题维护着一个观察者列表,并负责通知它们状态的改变。 2. **观察者(Observer)**:观察者关注主题,当主题状态改变时,观察者会收到通知并执行相应的操作。 3. **通知(Notification)**:当主题状态改变时,它会...
总结来说,这个"java观察者模式实例"帮助我们理解如何在实际项目中应用观察者模式,以及如何利用Java的`Observable`和`Observer`接口来实现。通过这个实例,我们可以更好地掌握Java的继承和多态特性,提升软件设计的...
- 支持广播通信,一个对象状态的改变可以同时通知多个对象。 - 它遵循“开闭原则”,即对扩展开放,对修改关闭。 然而,观察者模式也有一些潜在的问题: - 如果观察者数量过多,通知可能会影响性能。 - 如果不妥善...
Java观察者模式是一种设计模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。这种模式在软件工程中广泛应用,尤其在事件驱动和发布/订阅系统中。...
`Observable`类代表被观察的对象,它可以有多个观察者;`Observer`接口则代表观察者,它们需要实现`update`方法来接收被观察对象状态变化的通知。 以下是一个简单的Java观察者模式的示例: ```java import java....
`Observable`类代表被观察的对象,它可以有多个观察者,而`Observer`接口则定义了观察者的通用行为。 首先,我们需要了解`Observable`类的基本用法。这个类有一个`observers`集合,用来存储所有注册的观察者对象。...
观察者模式(Observer Pattern)是设计模式中的一种行为模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并被自动更新。这种模式常用于实现事件驱动的编程模型...
`Observable`类代表被观察的对象,它可以添加多个观察者,并在状态变化时通知它们。而`Observer`接口则定义了观察者的接口,需要实现`update`方法来处理接收到的通知。 实例代码通常会包含以下步骤: 1. 创建一个`...
### Java观察者模式详解 #### 一、观察者模式概述 观察者模式是一种常用的设计模式,主要用于处理对象间的一对多依赖关系。当一个对象(主题)的状态发生变化时,所有依赖于它的对象(观察者)都会收到通知并自动...
观察者模式(Observer Pattern)是软件设计模式中的一种行为模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。在Java中,我们可以利用Java提供的...
观察者模式(Observer Pattern)是设计模式中的一种行为模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并被自动更新。这种模式常用于事件驱动的系统或者实时...
观察者模式(Observer Pattern)是设计模式中的一种行为模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并被自动更新。这种模式常用于事件驱动编程,使得多个...
总结来说,这个未使用Java工具类的观察者模式演示展示了如何从零开始构建一个观察者模式的框架。通过自定义Subject和Observer,我们可以更自由地定制事件通知的逻辑,同时也加深了对观察者模式核心概念的理解。在...
在这个名为“运用MVC模式及观察者模式的java小程序”的项目中,我们重点探讨了两种经典的设计模式:Model-View-Controller(MVC)模式和Observer(观察者)模式。这两种模式在JavaWeb开发中扮演着至关重要的角色。 ...