Java设计模式之观察者

1.什么是观察者模式?

有时被称作发布/订阅模式,观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。
上面的解释太书面化了,举个生活中例子,小区中有100户业主向杂志社订阅了一本月刊杂志,每月的10号会发送给业主。这当中100户就是观察者,杂志社就是被观察者,订阅杂志的行为就是观察者模式中的订阅,每月10号就是观察者模式中的发布。==观察者模式的核心概念是一对多==。

2.观察者模式解决的问题

将一个系统分割成一个一些类相互协作的类有一个不好的副作用,那就是需要维护相关对象间的一致性。我们不希望为了维持一致性而使各类紧密耦合,这样会给维护、扩展和重用都带来不便。观察者就是解决这类的耦合关系的

3.观察者模式中的各个角色

Observer(抽象接口):观察者抽象接口,一般定义了观察者的抽象行为

Observerable(抽象类):被观察者抽象类,含有一个存储观察者对象的集合

ConcreteObserver(具体的观察者):实现Observer接口

ConcreteObserverable(具体的被观察者):继承Observerable抽象类

4.观察者模式的代码实现

观察者模式的代码一般有2种,可以完全由自己代码实现逻辑,也可以借助java api来实现。
自己实现代码如下:

Observer

public interface Observer<T> {

    void update(T t);
}

Observerable

public abstract class Observerable {

    //用来存储观察者的集合
    private List<Observer> obervers = new ArrayList<>();

    /**
     * 订阅事件
     * @param observer
     */
    public void subscribe(Observer observer){
        obervers.add(observer);
    }

    /**
     * 取消订阅
     * @param observer
     */
    public void unSubscribe(Observer observer){
        obervers.remove(observer);
    }

    /**
     * 通知广播
     * @param obj
     */
    public void notification(Object obj){
        for (Observer o : obervers) {
            o.update(obj);
        }
    }
}

ConcreteObserver

public class ReaderOberver implements Observer<String> {

    private String name;

    public ReaderOberver(String name){
        this.name = name;
    }

    @Override
    public void update(String s) {
        System.out.println(name+" get message is "+s);
    }

}

ConcreteObserverable

public class CompanyObserverable extends Observerable {

    public void sendMessage(String message){
        System.out.println("company send message : " +message);
        notification(message);
    }

}

执行测试代码

public class Main {

    public static void main(String[] args) {
        //1.创建一个被观察者对象
        CompanyObserverable observerable = new CompanyObserverable();
        //2.创建两个观察者对象
        ReaderOberver readA = new ReaderOberver("Read A");
        ReaderOberver readB = new ReaderOberver("Read B");
        //3.把这两个观察者对象注册到被观察者对象的集合中,俗称订阅
        observerable.subscribe(readA);
        observerable.subscribe(readB);
        //4.被观察者触发广播
        observerable.sendMessage(" The Message ");
    }
}

执行结果

company send message :  The Message 
Read A get message is  The Message 
Read B get message is  The Message 

总结:上面的例子很好的实现了观察者模式,重点就是一对多,但是这种写法是线程不安全的。所以介绍下java api的写法,它解决了线程安全的问题。

用java api实现观察者模式主要使用以下两个类

import java.util.Observable;
import java.util.Observer;

先看使用
ConcreteObserver

public class ReaderObserver implements Observer {

    private String name;

    public ReaderObserver(String name){
        this.name = name;
    }

    @Override
    public void update(Observable o, Object arg) {
        System.out.println(name +" get message is "+ arg.toString()+" from "+((CompanyObserverable)o).getName());
    }
}

ConcreteObserverable

public class CompanyObserverable extends Observable {

    private String name;

    public CompanyObserverable(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void sendMessage(String message){
        System.out.println(name+" send message :"+message);
        setChanged();
        notifyObservers(message);
    }

}

执行测试代码

public class Main {

    public static void main(String[] args){
        //1.创建一个被观察者对象
        CompanyObserverable observerable = new CompanyObserverable("company");
        ReaderObserver observerA = new ReaderObserver("observerA");
        ReaderObserver observerB = new ReaderObserver("observerB");
        //2.创建两个观察者对象
        observerable.addObserver(observerA);
        observerable.addObserver(observerB);
        //4.被观察者触发广播
        observerable.sendMessage(" The message ");
    }

}

执行结果

company send message : The message 
observerB get message is  The message  from company
observerA get message is  The message  from company

两种写法的结果是一样的,那么我们去看看系统的Observer和Observerable的源码,看看他是怎么工作的,为什么能解决线程安全的问题,代码不多,我就直接贴出来了

Observable.java

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();
    }
}

Observer.java

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这个借口非常简单,跟我们自己定义基本没差。而Observable这个类明显比我们定义要复杂一点,我们看重点
先看成员变量

private boolean changed = false;
private Vector<Observer> obs;

changed属性用来标记观察者集合中的书籍有没有改变,所以我们在发布前调用了setChanged(),否则不能正常发布。

obs属性用来存储观察者对象集合,这里用到了Vector集合对象类型,看到这里应该明白为什么系统提供的方案是线程安全的。

注:用CopyOnWriteArrayList这个集合框架类可以替代Vector会更好。

5.观察者模式在android中运用

1.观察者模式之回调模式

在android中回调模式无处不在,不管是系统api代码还是我们自己的业务代码,几乎天天都在写回调。其实回调模式就是一种简单的观察者模式,区别是回调模式是1对1的,观察者模式是1对n的。举一个android中最常见的例子,Button和OnClickListener之间的关系,Button就是被观察者,OnClickListener就是观察者的接口定义,OnClickListener的实现就是真正的观察者,只不过Button并没有存储OnClickListener实现的集合,只有存储着一个实例而已。

2.listview中的notifyDataChanged方法

notifyDataChanged这方法对于做android的人来说,熟悉了不能再熟悉了,但似乎从来没有归根探究。其实他内部就是用到了观察者模式用于当数据改变中通知view更新操作,由于源码比较复杂,这里就不做展开了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容