程序员人生 网站导航

通过Java源码分析初探观察者模式(一)

栏目:综合技术时间:2016-06-21 11:43:19

对视察者,很多开发者其实不陌生,在平常开发进程中,这也是1个非常常见的设计模式,特别是Android小火伴,很多人都知道broadcast就是1个典型的视察者模式,还有最近很火的rxjava,响应式编程中,视察者模式扮演着1个很重要的角色,但视察者模式具体是怎样样运转的,部份小火伴就有点模糊了。

先从平常生活中1个例子开始说起,在看电视的进程中,我们常常看到1些抗日神剧中有这么1个剧情,鬼子进村,在进村的进程中,总会有1些1些人透风报信,然后通知村里的人能躲的躲,能藏的藏,能跑的跑,或中路再弄个埋伏,抓到了以后是手撕还是其它方式处理,在此就先不做讨论。。。其实这个进程中就是1个典型的视察者模式,下面,我们先看1下手撕鬼子的UML。

这里写图片描述

DevilsSubject.java

/** * * created by zm on 2016⑸⑵8 * 继承Observable,此类同等于上述UML的Devil(小鬼子),其它对号入坐 * 视察鬼子是不是来攻击 * */ public class DevilsSubject extends Observable { private String assault; public String isAssault() { return assault; } public void setAssault(String assault) { this.assault = assault; //可通过this.hasChanged()获得是不是产生改变,这里我们统1设置成改变,以便测试 this.setChanged(); this.notifyObservers(assault); } }

VillagerObserver.java

/** * * created by zm on 2016⑸⑵8 * * VillagerObserver(放哨的村民),视察小鬼子行动 * */ public class VillagerObserver implements Observer { public void update(Observable o, Object obj) { // TODO Auto-generated method stub String assault = (String) obj; System.out.println(assault); } }

Client.java

public class Client { public static void main(String[] args) { VillagerObserver yes = new VillagerObserver(); VillagerObserver no = new VillagerObserver(); DevilsSubject devilsSubject = new DevilsSubject(); //如果视察者与集合中已有的视察者不同,则向对象的视察者集中添加此视察者。 devilsSubject.addObserver(yes); devilsSubject.addObserver(no); devilsSubject.setAssault("前方有1坨鬼子来了"); devilsSubject.setAssault("鬼子见阎王了,在来村的路上就被村民手撕了"); //返回 Observable 对象的视察者数目 System.out.println(devilsSubject.countObservers()); System.out.println("................"); devilsSubject.deleteObserver(yes); devilsSubject.setAssault("鬼子来了"); System.out.println(devilsSubject.countObservers()); } }

运行的结果:

前方有1坨鬼子来了 前方有1坨鬼子来了 鬼子见阎王了,在来村的路上就被村民手撕了 鬼子见阎王了,在来村的路上就被村民手撕了 Observable对象的视察者数目:2................ 鬼子来了 Observable对象的视察者数目:1

下面是observable源码

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 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 * @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<Observer> 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的api
这里写图片描述

根据源码中最上部份的注释,翻译成中文后,大体的意思是此类是1个被视察者。它可以派生子类来表示1个利用程序想要视察的对象。1个可视察到的对象(observable)可以有1个或多个视察者(observer)。1个视察者可以是任何实现接口的视察者的对象。修改后可视察到的实例,利用程序调用notifyObservers方法使所有的视察者调用更新方法。通知的顺序将是未指定的。请注意,这与线程通知机制无关,完全独立于类对象的等待和通知机制。当1个可视察的对象是新创建的,它的视察是空的。当且仅当这个方法返回true,两个视察者是同步的。

源码中,起关键性作用的就是vector和changed,在observable实例化的时候,就初始化了1个空的vector,可以通过vector添加和移除vector操作后,当observable产生改变时,通过changed去判断是不是通知,在我们的上述示例代码中使用setChanged(),主要是由于第1次加入的时候,不会去调用observer的update方法,也就是changed为false,当changed为false时,直接从notifyObservers方法中return,只有changed为true的时候才通知刷新,刷新之前,重新把changed赋值为false,提取上述源码中的关键代码以下:

public void notifyObservers(Object arg) { Object[] arrLocal; synchronized (this) { if (!changed) return; arrLocal = obs.toArray(); clearChanged(); } for (int i = arrLocal.length-1; i>=0; i--) ((Observer)arrLocal[i]).update(this, arg); }

observer类

/** * A class can implement the <code>Observer</code> interface when it * wants to be informed of changes in observable objects. * * @author Chris Warth * @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); }

observer就是1个接口,里面1个update方法,这个类没太多需要解释的,有点Java基础的都可以明白。

现在1目了然了,Observer模式是1种行动模式,它的作用是当1个对象的状态产生改变的时候,能够自动通知其他关联对象,自动刷新对象状态。Observer模式提供给关联对象1种同步通讯的手段,使其某个对象与依赖它的其他对象之间保持状态同步。

抽象主题角色(Subject)内部其实就是1个Vector,在addObserver的时候,就把需要的视察者添加到Vector中。在deleteObserver的时候,就把传进来的视察者从容器中移除掉。主题角色又叫抽象被视察者角色(observable),1般用1个抽象类或接口来实现。

observable与observer是1种1对多的依赖关系,可让多个视察者对象同时监听某1个主题对象。视察者模式有时被称作发布/定阅模式(Publish/Subscribe),对这名称很贴切的,就好比我们定阅了报纸,每次报社新报纸出版发售的时候,就会根据定阅的客户逐一发报纸,通知客户浏览。

ConcreteSubject:具体主题角色,将相干状态存入具体视察者对象。具体主题角色又叫具体被视察者角色(ConcreteObservable)。

ConcreteObserver:具体视察者角色,实现抽象视察者角色(observer)所需要的更新接口,以便使自己状态和主题状态相调和。

这里写图片描述

总结:通过依赖抽象而不是依赖具体类,去实现1个类中某个状态的改变,而通知相干的1些类去做出相应的改变,进而保持同步状态。实现这样的方式也许有很多种,但是为了使系统能够易于复用,应当选择第耦合度的方案。减少对象之间的耦合度有益于系统的复用,在保证低耦合度的条件下并且能够保持行动的调和1致,保证高度协作,视察者模式是1种很好的设计方案。

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐