`
chenhua_1984
  • 浏览: 1251996 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

Java 观察者模式observer

阅读更多

    观察者模式:顾名思义就是有个人在观察着一些东西,一旦这些东西发生了变化,观察者就可以第一时间知道这个情况。就像现在的电影里的间谍跟踪一样的,老大在家里指挥,小弟在外面跟踪观察动态,一旦敌人有什么异动,小弟马上就知道了,然后通知家里的老大。大致就是这么一个过程。

   既然是观察者模式,那么自然就有观察者,被观察者这几个对象实体。jdk为观察者模式提供了很好的支持,在java.util这个包里面,有观察的接口Observer,和可观察这个接口Observable,代码如下

Observer.java
/*
 * @(#)Observer.java	1.20 05/11/17
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package java.util;

/**
 * A class can implement the <code>Observer</code> interface when it
 * wants to be informed of changes in observable objects.
 *
 * @author  Chris Warth
 * @version 1.20, 11/17/05
 * @see     java.util.Observable
 * @since   JDK1.0
 */
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

/*
 * @(#)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中要想实现观察者模式,那么观察者要时间Observer接口,被观察者要继承Observable这个类。下面是一个简单的例子。

观察者一:

JavaJMSObserver。Java

import java.util.Observable;
import java.util.Observer;

public class JavaJMSObserver implements Observer{

	public void update(Observable o, Object arg) {
		System.out.println("发送消息给jms服务器的观察者已经被执行�");
	}
}

 观察者二:

   SendMailObserver.java

import java.util.Observable;
import java.util.Observer;

public class SendMailObserver implements Observer{

	
	public void update(Observable o, Object arg) {
		System.out.println("�����ʼ��Ĺ发送邮件的观察者已经被执行��");
	}

}

 被观察者:‘

Subject.java

import java.util.Observable;
import java.util.Observer;

public class Subject extends Observable{
	
	/**
	 * 业务方法,一旦执行某个操作,则通知观察者
	 */
	public void doSomething(){
		//........
		super.setChanged();
		notifyObservers("现在还没有的参数�û�еIJ���");
	}

	
	public static void main(String [] args) {
		//创建一个被观察者���
		Subject subject = new Subject();
		
		//创建两个观察者���
		Observer sendMailObserver = new SendMailObserver();
		Observer javaJmsObserver = new JavaJMSObserver();
		
		//把两个观察者加到被观察者列表中����б���
		subject.addObserver(sendMailObserver);
		subject.addObserver(javaJmsObserver);
		
		//执行业务操作�����
		subject.doSomething();
	}
}
 
0
0
分享到:
评论
1 楼 asialee 2010-01-09  
这里实现的observer模式将发生变化的实体和一些参数相关参数都传递过来了。其实在例子里面可以体现这一点,观察者模式在实际的使用过程中可能会有点变通,有的使用场景是不需要知道是哪个被观察者发生的变化的。

相关推荐

    java观察者模式观察者模式

    在Java中,`java.util.Observable`类和`java.util.Observer`接口提供了对观察者模式的内置支持。`Observable`类代表被观察的对象,它可以有多个观察者,而`Observer`接口则定义了观察者的通用行为。 ### `...

    观察者模式Observer

    在Java中,`java.util.Observable`和`java.util.Observer`接口提供了内置的支持来实现观察者模式。开发者可以创建自己的类实现这两个接口,或者使用更现代的事件监听框架如JavaFX或Swing中的事件处理机制。 观察者...

    Java观察者模式代码全解析

    Java观察者模式是一种设计模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。这种模式在软件工程中广泛应用,尤其在事件驱动和发布/订阅系统中。...

    java观察者模式Demo

    标题中的“java观察者模式Demo”指的是使用Java语言来演示观察者模式的应用。通常,这个Demo会包含一个可观察的对象(Observable)和多个观察者(Observer),当可观察对象的状态发生变化时,会触发通知机制,使得...

    java 观察者模式 demo

    以下是一个简单的Java观察者模式的示例: ```java import java.util.Observable; import java.util.Observer; class WeatherData implements Observable { private float temperature; private float humidity; ...

    Java内置观察者模式

    观察者模式(Observer Pattern)是设计模式中的一种行为模式,它允许一个对象,当其状态发生改变时,能够自动通知所有依赖它的其他对象。在Java中,这种模式已经被内置到语言核心,使得开发者可以轻松地实现事件驱动...

    Java 观察者模式的浅析

    ### Java观察者模式详解 #### 一、观察者模式概述 观察者模式是一种常用的设计模式,主要用于处理对象间的一对多依赖关系。当一个对象(主题)的状态发生变化时,所有依赖于它的对象(观察者)都会收到通知并自动...

    设计模式之观察者模式(Observer Pattern)

    在Java、C#等面向对象编程语言中,观察者模式被广泛应用于用户界面、事件处理、游戏编程等领域。 在观察者模式中,通常有两个主要角色:主题(Subject)和观察者(Observer)。主题是被观察的对象,它持有一个观察...

    java 设计模式 观察者模式 简单实例 包括测试test类

    在Java中,观察者模式的实现通常基于Java的内置接口`java.util.Observer`和`java.util.Observable`。下面将详细解释观察者模式的概念、结构以及如何在Java中应用这个模式。 **观察者模式的核心概念:** 1. **主题...

    观察者模式observer

    在Java中,观察者模式的实现通常涉及到java.util.Observable和java.util.Observer接口。Observable类代表被观察的对象,Observer接口则表示观察者。当Observable对象的状态发生变化时,它会调用notifyObservers方法...

    设计模式之观察者模式(Observer)

    观察者模式在Java中得到了很好的支持,`java.util.Observable`和`java.util.Observer`是Java标准库提供的观察者模式实现。开发者可以方便地利用这两个类实现观察者模式,也可以根据实际需求自定义观察者接口和主题类...

    java观察者模式实例

    总结来说,这个"java观察者模式实例"帮助我们理解如何在实际项目中应用观察者模式,以及如何利用Java的`Observable`和`Observer`接口来实现。通过这个实例,我们可以更好地掌握Java的继承和多态特性,提升软件设计的...

    Java观察者模式代码

    在Java中,观察者模式的实现主要依赖于`java.util.Observable`类和`java.util.Observer`接口。`Observable`类代表被观察的对象,而`Observer`接口则表示观察者。下面我们将详细介绍如何在Java中实现观察者模式。 1....

    Java观察者模式案例

    以下是一个简单的Java观察者模式案例: ```java import java.util.ArrayList; import java.util.List; // 主题类(被观察者) class ObservableSubject extends Observable { private String state; public ...

    java 观察者模式经典案例

    在Java中,观察者模式是通过Java的内置接口`java.util.Observer`和`java.util.Observable`来实现的。 在"java 观察者模式经典案例"中,我们以报社和读者为例来讲解这一模式。假设报社是被观察者(Observable),...

    Java 设计模式-观察者模式(Observer)

    结合微信公众号讲解观察者模式,生动形象,关键是上手快啊

    观察者模式(Observer)

    在实际开发中,Java的`java.util.Observable`和`java.util.Observer`类提供了内置的观察者模式支持。而Spring框架中的`ApplicationEvent`和`ApplicationListener`也是观察者模式的应用,用于应用级别的事件监听。 ...

    观察者(Observer)模式

    观察者模式的核心概念是主体(Subject)和观察者(Observer)。主体是被观察的对象,它维护了一个观察者列表,并提供了添加、删除观察者以及通知所有观察者的接口。观察者关注主体的状态变化,并在主体状态改变时...

    观察者模式(Observer)

    观察者模式可以通过多种编程语言实现,例如在Java中,可以使用`java.util.Observable`和`java.util.Observer`接口。被观察者实现`Observable`接口,而观察者实现`Observer`接口。当被观察者状态改变时,调用`...

Global site tag (gtag.js) - Google Analytics