博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
设计模式--观察者模式[Observer]
阅读量:7115 次
发布时间:2019-06-28

本文共 11707 字,大约阅读时间需要 39 分钟。

本文地址:

转载请在明显位置标明出处

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  * 

33 * An observable object can have one or more observers. An observer 34 * may be any object that implements interface Observer. After an 35 * observable instance changes, an application calling the 36 * Observable's notifyObservers method 37 * causes all of its observers to be notified of the change by a call 38 * to their update method. 39 *

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 *

47 * Note that this notification mechanism is has nothing to do with threads 48 * and is completely separate from the wait and notify 49 * mechanism of class Object. 50 *

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 * equals 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 null 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 * hasChanged method, then notify all of its observers101 * and then call the clearChanged method to102 * indicate that this object has no longer changed.103 *

104 * Each observer has its update method called with two105 * arguments: this observable object and null. In other106 * words, this method is equivalent to:107 *

108 * notifyObservers(null)
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 * hasChanged method, then notify all of its observers121 * and then call the clearChanged method to indicate122 * that this object has no longer changed.123 *

124 * Each observer has its update method called with two125 * arguments: this observable object and the arg 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 Observable object as having been changed; the171 * hasChanged method will now return true.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 hasChanged method will now return false.181 * This method is called automatically by the182 * notifyObservers 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 true if and only if the setChanged195 * method has been called more recently than the196 * clearChanged method on this object;197 * false 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 Observable 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 Observer 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 Observable object's39      * notifyObservers 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 notifyObservers44      *                 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 
2
3 4
5
6 7
8
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   
30 31   
32   产品名称:
33   产品价格:
34   
35 36   
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  迭代时是从添加顺序反向迭代的(详细的请看源码)

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

 

转载于:https://www.cnblogs.com/masque/p/3831628.html

你可能感兴趣的文章
GDB 调试 Mysql 实战(三)优先队列排序算法中的行记录长度统计是怎么来的(上)...
查看>>
GoLand中的指针操作 * 和 &
查看>>
116. Populating Next Right Pointers in Each Node
查看>>
webpack 最简打包结果分析
查看>>
NLPIR:数据挖掘深度决定大数据应用价值
查看>>
laravel接入Consul
查看>>
Flex 布局教程
查看>>
GET和POST两种基本请求方法的区别
查看>>
Webpack4 学习笔记 - 01:webpack的安装和简单配置
查看>>
二)golang工厂模式
查看>>
React 教程:快速上手指南
查看>>
Python 的 heapq 模块源码分析
查看>>
Jitsi快捷安装
查看>>
区块链技术的基本特点
查看>>
阿里云容器服务DaemonSet实践
查看>>
一个游戏拨账系统的数据库结算设计
查看>>
Kafka Network层解析
查看>>
css加载会造成阻塞吗?
查看>>
由一个绝对定位引发overflow:auto滚动问题产生的关于包含块(containing block)的思考...
查看>>
CS-231N-斯坦福李飞飞机器视觉课(Cydiachen版笔记+感悟)
查看>>