`
chenhua_1984
  • 浏览: 1233960 次
  • 性别: 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 观察者模式的浅析 简单地说,观察者模式定义了一个一对多的依赖关系,让一个或多个观察者对象监察一个主题对象。这样一个主题对象在状态上的变化能够通知所有的依赖于此对象的那些观察者对象,使这些观察者...

    观察者模式Observer

    观察者模式Observer: 以手机号码为例,老师的手机号码存在学生的手机里,若老师的手机号改变,她会发一条短信通知每个学生自己手机号变了

    Java内置观察者模式

    观察者模式:对象之间多对一依赖的一种设计方案,被依赖的对象为Subject,依赖的对象为Observer,Subject通知Observer变化,这个例子是java内置观察者模式

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

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

    java观察者模式.doc

    在设计一组依赖的对象与它们所依赖的对象之间一致(同步)的交流模型时,观察者模式(Observer Pattern)很有用。它可以使依赖对象的状态与它们所依赖的对象的状态保持同步。这组依赖的对象指的是观察者(Observer)...

    Java观察者模式代码全解析

    一个很简单但是明了的java观察者模式的demo。备注几乎每行都加了。

    详解Observer Pattern(观察者模式)在Java中的使用原理

    我们说学习Java应该从Swing开始,那么学习Swing最重要的思想就是对于观察者模式的理解(Observer Pattern)。因为,该设计模式在Java Swing框架中贯穿了始终。对于C#的委托、代理概念所使用的Callback(回调模式--...

    java 观察者模式 demo

    开发中常用 设计模式 开发者模式,欢迎大家学习。 博客:http://blog.csdn.net/q610098308/article/details/76143959

    java实现观察者模式-Java内置的观察者模式(基于Observable和Observer)

    Java内置的Observable类和Observer接口提供了基本的观察者模式功能,你可以通过继承Observable类和实现Observer接口来使用

    java观察者模式介绍

    Observer模式定义对象间的一对多的依赖关系,当一个对象(被观察者)的状态发生改变时, 所有依赖于它的对象(观察者)都得到通知并被自动更新。JDK里提供的observer设计模式的实现由java.util.Observable类和 java....

    观察者模式(Observer)原理图

    观察者模式(Observer Pattern)是一种对象行为型设计模式,它定义了对象之间的一对多依赖关系。 当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。这种模式通常用于实现分布式事件处理系统...

    设计模式 观察者 发布/订阅 Observer

    Observer (观察者模式) 又叫做发布/订阅(Publish/Subscribe)模式。 当一个对象的改变同时会影响其他对象的行为的时候,可以使用此设计模式。 l 主题对象 :一个需要被关注的主题对象,这个主题对象改变会影响...

    观察者模式相关

    观察者 Observer 模式定义:在对象之间定义了一对多的依赖关系 这样一来 当一个对象改变状态时 依赖它的对象都会收到通知并自动跟新 Java已经提供了对观察者Observer模式的默认实现 Java对观察者模式的支持主要体现...

    java观察者模式demo----未使用java工具类

    观察者设计模式,java语言实现,完全自己代码实现,未使用observable和observer

    观察者模式的一个demo

    观察者模式的demo,工程文件,导入eclipse 可以直接使用。了解观察者模式!

    观察者(Observer)模式

    这是java程序言必学的一个设计模式,这个小例子阐述明确,通俗易懂。

    Java聊天室 观察者模式和单例模式

    基于观察者模式和单例模式的java聊天室 面向对象设计,抽象,封装,代理,组合和继承 适合理解java面向对象,socket编程,观察者模式和单例模式

    Java设计模式之观察者模式(Observer模式)介绍

    主要介绍了Java设计模式之观察者模式(Observer模式)介绍,Java深入到一定程度,就不可避免的碰到设计模式(design pattern)这一概念,了解设计模式,将使自己对java中的接口或抽象类应用有更深的理解,需要的朋友可以...

    观察者模式

    Java 观察者模式的浅析 Java 观察者模式的浅析 Java 观察者模式的浅析

    Java 观察者模式

    利用气象站监测的例子详细介绍观察者模式的使用方法,具体介绍观察者模式的所适应的场景情况

Global site tag (gtag.js) - Google Analytics