设计模式之观察者模式

来源:互联网 发布:乐视投屏 for mac 编辑:程序博客网 时间:2024/05/22 19:00

一、简介

观察者模式(Observer Pattern)也叫做发布订阅模式(Publish/subscribe):定义对象间一种一对多的依赖关系,使得每当一个对象改变状态,则所有依赖于它的对象都会得到通知并自动更新。

观察者模式的优点:

  • 观察者和被观察者之间是抽象耦合(不管是增加观察者还是被观察者都非常容易扩展)
  • 建立一套触发机制

观察者模式的缺点:(开发效率与运行效率)

  • 一个被观察者,多个观察者,开发和调试就会比较复杂,而且在Java中消息的通知默认是顺序执行的,一个观察者卡壳了,会影响整体的执行效率。这种情况下,一般考虑采用异步方式。
  • 多级触发时的效率更是让人担忧。

观察者模式的使用场景:

  • 关联行为场景。需要注意的是,关联行为是可拆分的,而不是“组合”关系。
  • 事件多级触发场景。
  • 跨系统的消息交换场景,如消息队列的处理机制。

注意事项:

  • 广播链的问题。(一个观察者可以有双重身份,也就是说其也可以是被观察者,一旦产生连锁反应,这个逻辑就相对复杂,可维护性就相对较差,所以这种双重身份的观察者应当尽量少比较好)
  • 异步处理问题。(需要考虑线程安全和队列的问题)

注意:

  观察者模式的广播链和责任链模式的最大区别就是观察者模式在传播的过程中消息是随时更改的,他是由相邻的两个节点协商的消息结构;而责任链模式在消息传递过程中基本上保持消息不可变,如果要改变,也只是在原有的消息上进行修改。


二、详解

1. 观察者通用类图

其中的角色:

  • Subject(被观察者),必须能够动态地增加或删除观察者,并能够通知观察者。
  • Observer(观察者)
  • ConcreteSubject(具体的被观察者),定义被观察者自己的业务逻辑,同时定义对那些事件进行通知。
  • ConcreteObbserver(具体的观察者)

观察者:

public interface Observer {//更新方法public void update();}
具体观察者:
public class ConcreteObserver implements Observer {@Overridepublic void update() {System.out.println("观察者接收到消息。。。。。");}}
被观察者:
import java.util.Vector;public abstract class Subject {//定义一个观察者数组private Vector<Observer> obsVector = new Vector<Observer>();//增加一个观察者public void addObserver(Observer o){this.obsVector.add(o);}//删除一个观察者public void delObserver(Observer o){this.obsVector.remove(o);}//通知所有观察者public void notifyObserver(){for (Observer o : obsVector) {o.update();}}}
具体被观察者:
public class ConcreteSubject extends Subject {//具体的业务public void doSomething(){System.out.println("被监视者活动了。。。。。");super.notifyObserver();}}
场景:

public class Client {public static void main(String[] args) {//创建一个被观察者ConcreteSubject subject = new ConcreteSubject();//创建一个观察者Observer obs = new ConcreteObserver();//将观察者加入到被观察者中subject.addObserver(obs);//被观察者活动subject.doSomething();}}
运行结果:

被监视者活动了。。。。。观察者接收到消息。。。。。

2.Java世界中的观察者

JDK中提供了:java.util.Observable实现类和java.util.Observer接口,被观察者需要继承Observable,观察者需要实现Observer接口。

Java中的观察者类图:


Observable的源代码:(不想细看可以直接看API)

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内部包含了两个变量:boolean changed与Vector<Observer> obs,分别是当前被观察者的状态,与注册的观察者,开始时默认的观察者为空。只有当被观察者的状态为true(改变状态)时,才可以执行notifyObservers()函数通知所有的观察者,当然可以带有参数测传递。

  观察者只需要实现Observer接口就可以了。

API给出的解释是:

  一个 observable 对象可以有一个或多个观察者。观察者可以是实现了 Observer 接口的任意对象。一个 observable 实例改变后,调用 Observable 的 notifyObservers 方法的应用程序会通过调用观察者的 update 方法来通知观察者该实例发生了改变。

  未指定发送通知的顺序。Observable 类中所提供的默认实现将按照其注册的重要性顺序来通知 Observers,但是子类可能改变此顺序,从而使用非固定顺序在单独的线程上发送通知,或者也可能保证其子类遵从其所选择的顺序。
注意,此通知机制与线程无关,并且与 Object 类的 wait 和 notify 机制完全独立。
新创建一个 observable 对象时,其观察者集是空的。当且仅当 equals 方法为两个观察者返回 true 时,才认为它们是相同的。

使用Java提供的观察者模式非常简单,所以在Java的世界里多看看API,有很大帮助,很多东西Java已经帮我们设计了一个良好的框架了。


参考资料:
《设计模式之禅》
《Java设计模式》

********************************************************************************结束语********************************************************************************************
  我在写这篇博客的时候也是一名初学者,有任何疑问或问题请留言,或发邮件也可以,邮箱为:577328725@qq.com,我会尽早的进行更正及更改。
在我写过的博客中有两篇博客是对资源的整理,可能对大家都有帮助,大家有兴趣的话可以看看!!
下载资料整理——目录:http://blog.csdn.net/fanxiaobin577328725/article/details/51894331
  这篇博客里面是我关于我见到的感觉不错的好资源的整理,里面包含了书籍及源代码以及个人搜索的一些资源,如果有兴趣的可以看看,我会一直对其进行更新和添加。
优秀的文章&优秀的学习网站之收集手册:http://blog.csdn.net/fanxiaobin577328725/article/details/52753638
  这篇博客里面是我对于我读过的,并且感觉有意义的文章的收集整理,纯粹的个人爱好,大家感觉有兴趣的可以阅读一下,我也会时常的对其进行更新。
********************************************************************************感谢********************************************************************************************

0 0
原创粉丝点击