首页 > 代码库 > 设计模式--观察者模式

设计模式--观察者模式

 

jdk自带了观察者模式的接口 java.util.Observer  和  类java.util.Observable

下面是源码 java.util.Observable

  1 /*  2  * Copyright (c) 1994, 2004, Oracle and/or its affiliates. All rights reserved.  3  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.  4  *  5  *  6  *  7  *  8  *  9  * 10  * 11  * 12  * 13  * 14  * 15  * 16  * 17  * 18  * 19  * 20  * 21  * 22  * 23  * 24  */ 25  26 package java.util; 27  28 /** 29  * This class represents an observable object, or "data" 30  * in the model-view paradigm. It can be subclassed to represent an 31  * object that the application wants to have observed. 32  * <p> 33  * An observable object can have one or more observers. An observer 34  * may be any object that implements interface <tt>Observer</tt>. After an 35  * observable instance changes, an application calling the 36  * <code>Observable</code>‘s <code>notifyObservers</code> method 37  * causes all of its observers to be notified of the change by a call 38  * to their <code>update</code> method. 39  * <p> 40  * The order in which notifications will be delivered is unspecified. 41  * The default implementation provided in the Observable class will 42  * notify Observers in the order in which they registered interest, but 43  * subclasses may change this order, use no guaranteed order, deliver 44  * notifications on separate threads, or may guarantee that their 45  * subclass follows this order, as they choose. 46  * <p> 47  * Note that this notification mechanism is has nothing to do with threads 48  * and is completely separate from the <tt>wait</tt> and <tt>notify</tt> 49  * mechanism of class <tt>Object</tt>. 50  * <p> 51  * When an observable object is newly created, its set of observers is 52  * empty. Two observers are considered the same if and only if the 53  * <tt>equals</tt> method returns true for them. 54  * 55  * @author  Chris Warth 56  * @see     java.util.Observable#notifyObservers() 57  * @see     java.util.Observable#notifyObservers(java.lang.Object) 58  * @see     java.util.Observer 59  * @see     java.util.Observer#update(java.util.Observable, java.lang.Object) 60  * @since   JDK1.0 61  */ 62 public class Observable { 63     private boolean changed = false; 64     private Vector obs; 65  66     /** Construct an Observable with zero Observers. */ 67  68     public Observable() { 69         obs = new Vector(); 70     } 71  72     /** 73      * Adds an observer to the set of observers for this object, provided 74      * that it is not the same as some observer already in the set. 75      * The order in which notifications will be delivered to multiple 76      * observers is not specified. See the class comment. 77      * 78      * @param   o   an observer to be added. 79      * @throws NullPointerException   if the parameter o is null. 80      */ 81     public synchronized void addObserver(Observer o) { 82         if (o == null) 83             throw new NullPointerException(); 84         if (!obs.contains(o)) { 85             obs.addElement(o); 86         } 87     } 88  89     /** 90      * Deletes an observer from the set of observers of this object. 91      * Passing <CODE>null</CODE> to this method will have no effect. 92      * @param   o   the observer to be deleted. 93      */ 94     public synchronized void deleteObserver(Observer o) { 95         obs.removeElement(o); 96     } 97  98     /** 99      * If this object has changed, as indicated by the100      * <code>hasChanged</code> method, then notify all of its observers101      * and then call the <code>clearChanged</code> method to102      * indicate that this object has no longer changed.103      * <p>104      * Each observer has its <code>update</code> method called with two105      * arguments: this observable object and <code>null</code>. In other106      * words, this method is equivalent to:107      * <blockquote><tt>108      * notifyObservers(null)</tt></blockquote>109      *110      * @see     java.util.Observable#clearChanged()111      * @see     java.util.Observable#hasChanged()112      * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)113      */114     public void notifyObservers() {115         notifyObservers(null);116     }117 118     /**119      * If this object has changed, as indicated by the120      * <code>hasChanged</code> method, then notify all of its observers121      * and then call the <code>clearChanged</code> method to indicate122      * that this object has no longer changed.123      * <p>124      * Each observer has its <code>update</code> method called with two125      * arguments: this observable object and the <code>arg</code> argument.126      *127      * @param   arg   any object.128      * @see     java.util.Observable#clearChanged()129      * @see     java.util.Observable#hasChanged()130      * @see     java.util.Observer#update(java.util.Observable, java.lang.Object)131      */132     public void notifyObservers(Object arg) {133         /*134          * a temporary array buffer, used as a snapshot of the state of135          * current Observers.136          */137         Object[] arrLocal;138 139         synchronized (this) {140             /* We don‘t want the Observer doing callbacks into141              * arbitrary code while holding its own Monitor.142              * The code where we extract each Observable from143              * the Vector and store the state of the Observer144              * needs synchronization, but notifying observers145              * does not (should not).  The worst result of any146              * potential race-condition here is that:147              * 1) a newly-added Observer will miss a148              *   notification in progress149              * 2) a recently unregistered Observer will be150              *   wrongly notified when it doesn‘t care151              */152             if (!changed)153                 return;154             arrLocal = obs.toArray();155             clearChanged();156         }157 158         for (int i = arrLocal.length-1; i>=0; i--)159             ((Observer)arrLocal[i]).update(this, arg);160     }161 162     /**163      * Clears the observer list so that this object no longer has any observers.164      */165     public synchronized void deleteObservers() {166         obs.removeAllElements();167     }168 169     /**170      * Marks this <tt>Observable</tt> object as having been changed; the171      * <tt>hasChanged</tt> method will now return <tt>true</tt>.172      */173     protected synchronized void setChanged() {174         changed = true;175     }176 177     /**178      * Indicates that this object has no longer changed, or that it has179      * already notified all of its observers of its most recent change,180      * so that the <tt>hasChanged</tt> method will now return <tt>false</tt>.181      * This method is called automatically by the182      * <code>notifyObservers</code> methods.183      *184      * @see     java.util.Observable#notifyObservers()185      * @see     java.util.Observable#notifyObservers(java.lang.Object)186      */187     protected synchronized void clearChanged() {188         changed = false;189     }190 191     /**192      * Tests if this object has changed.193      *194      * @return  <code>true</code> if and only if the <code>setChanged</code>195      *          method has been called more recently than the196      *          <code>clearChanged</code> method on this object;197      *          <code>false</code> otherwise.198      * @see     java.util.Observable#clearChanged()199      * @see     java.util.Observable#setChanged()200      */201     public synchronized boolean hasChanged() {202         return changed;203     }204 205     /**206      * Returns the number of observers of this <tt>Observable</tt> object.207      *208      * @return  the number of observers of this object.209      */210     public synchronized int countObservers() {211         return obs.size();212     }213 }
View Code

源码 java.util.Observer 

 1 /* 2  * Copyright (c) 1994, 1998, Oracle and/or its affiliates. All rights reserved. 3  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. 4  * 5  * 6  * 7  * 8  * 9  *10  *11  *12  *13  *14  *15  *16  *17  *18  *19  *20  *21  *22  *23  *24  */25 package java.util;26 27 /**28  * A class can implement the <code>Observer</code> interface when it29  * wants to be informed of changes in observable objects.30  *31  * @author  Chris Warth32  * @see     java.util.Observable33  * @since   JDK1.034  */35 public interface Observer {36     /**37      * This method is called whenever the observed object is changed. An38      * application calls an <tt>Observable</tt> object‘s39      * <code>notifyObservers</code> method to have all the object‘s40      * observers notified of the change.41      *42      * @param   o     the observable object.43      * @param   arg   an argument passed to the <code>notifyObservers</code>44      *                 method.45      */46     void update(Observable o, Object arg);47 }
View Code

分析下源码你就会发现实现其实原理很简单

java.util.Observable中定义了一个集合用来封装观察者.

当被观察者发生变化时我们就迭代这个集合调用都有的观察者方法(update)

 

其实也可以在被观察者的set方法中调用.

我们必须extends Java.util.Observer才能真正使用它:
1.提供Add/Delete
observer的方法;
2.提供通知(notisfy) 所有observer的方法;

 1 //产品类 可供Jsp直接使用UseBean调用 该类主要执行产品数据库插入 更新 2 public class product extends Observable{  3  4   private String name; 5   private float price; 6  7   public String getName(){ return name;} 8   public void setName(){ 9    this.name=name;10   //设置变化点 11    setChanged();12    notifyObservers(name);13 14   }   15 16   public float getPrice(){ return price;}17   public void setPrice(){18    this.price=price;19   //设置变化点20    setChanged();21    notifyObservers(new Float(price)); 22 23   }24 25   //以下可以是数据库更新 插入命令.26   public void saveToDb(){27   .....................28 29 }

我们注意到,在product类中 的setXXX方法中,我们设置了 notify(通知)方法, 当Jsp表单调用setXXX(如何调用见我的另外一篇文章),实际上就触发了notisfyObservers方法,这将通知相应观察者应该采取行动了.

下面看看这些观察者的代码,他们究竟采取了什么行动:

 1 //观察者NameObserver主要用来对产品名称(name)进行观察的 2 public class NameObserver implements Observer{ 3  4   private String name=null; 5  6   public void update(Observable obj,Object arg){ 7  8     if (arg instanceof String){ 9 10      name=(String)arg;11      //产品名称改变值在name中12      System.out.println("NameObserver :name changet to "+name);13 14     }15 16   }17 18 }19 20 //观察者PriceObserver主要用来对产品价格(price)进行观察的21 public class PriceObserver implements Observer{22 23   private float price=0;24 25   public void update(Observable obj,Object arg){26 27     if (arg instanceof Float){28 29      price=((Float)arg).floatValue();30   31      System.out.println("PriceObserver :price changet to "+price);32 33     }34 35   }36 37 }

 1 <jsp:useBean id="product" scope="session" class="Product" /> 2 <jsp:setProperty name="product" property="*" /> 3  4 <jsp:useBean id="nameobs" scope="session" class="NameObserver" /> 5 <jsp:setProperty name="product" property="*" /> 6  7 <jsp:useBean id="priceobs" scope="session" class="PriceObserver" /> 8 <jsp:setProperty name="product" property="*" /> 9 10 <%11 12 if (request.getParameter("save")!=null)13 { 14   product.saveToDb();15 16 17   out.println("产品数据变动 保存! 并已经自动通知客户"); 18 19 }else{20 21   //加入观察者22   product.addObserver(nameobs);23 24   product.addObserver(priceobs);25 26 %>27 28   //request.getRequestURI()是产生本jsp的程序名,就是自己调用自己29   <form action="<%=request.getRequestURI()%>" method=post>30 31   <input type=hidden name="save" value="http://www.mamicode.com/1">32   产品名称:<input type=text name="name" >33   产品价格:<input type=text name="price">34   <input type=submit>35 36   </form>37 38 <%39 40 } 41 42 %>43  

执行改Jsp程序,会出现一个表单录入界面, 需要输入产品名称 产品价格, 点按Submit后,还是执行该jsp的 if (request.getParameter("save")!=null)之间的代码.
由于这里使用了数据javabeans的自动赋值概念,实际程序自动执行了setName setPrice语句.你会在服务器控制台中发现下面信息:: NameObserver :name changet to ?????(Jsp表单中输入的产品名称)
PriceObserver :price changet to ???(Jsp表单中输入的产品价格);

这说明观察者已经在行动了.!! 同时你会在执行jsp的浏览器端得到信息:
产品数据变动 保存! 并已经自动通知客户

上文由于使用jsp概念,隐含很多自动动作,现将调用观察者的Java代码写如下:

 1 public class Test { 2  3   public static void main(String args[]){ 4  5 Product product=new Product(); 6  7 NameObserver nameobs=new NameObserver(); 8 PriceObserver priceobs=new PriceObserver(); 9 10 //加入观察者11 product.addObserver(nameobs);12 product.addObserver(priceobs);13 14 product.setName("橘子红了");15 product.setPrice(9.22f); 16 17   }18 19 }

你会在发现下面信息:: NameObserver :name changet to 橘子红了
PriceObserver :price changet to 9.22

这说明观察者在行动了.!!

 缺点,无法按照指定的顺序通知观察者,因为父类中是Vector  迭代时是从添加顺序反向迭代的(详细的请看源码)

有特殊需求时可以自己实现观察者模式