美文网首页
观察者模式

观察者模式

作者: wervy | 来源:发表于2020-01-28 11:50 被阅读0次
定义

定义一对多的依赖关系,让多个观察者对象同时监听某一个主题对象,这个主题对象在状态上发生变化时,会通知所有观察者对象,使它们能够自动更新

角色介绍

  • Subject :抽象主题,也就是被观察(Observale)的角色,抽象主题角色把所有观察则对象的引用保存在一个集合里,每个主题都可以有任意数量的观察者,抽象主题提供一个接口,可以增加和删除观察者对象。
  • ConcreteSubject: 具体主题,该角色将有关状态存入具体观察者对象,在具体主题的内部状态发生改变时,给所有注册过的观察者发出通知,具体主题角色又叫做具体被观察者(Concrete Observable)角色
  • Observer:抽象观察者,该角色是观察者的抽象类,它定义了一个更新接口,以便在主题的状态发生变化时更新自身的状态。
  • ConcreteObserver: 具体的观察者,该角色实现抽象观察者角色所定义的更新接口,以便在主题的状态发生变化时,更新自身的状态。

代码示例如下:

抽象被观察者

public interface Observable { //抽象被观察者

    void add(Observer observer); //添加观察者

    void remove(Observer observer); //删除观察者

    void notify(String observer); //通知观察者


}

具体被观察者

import java.util.ArrayList;
import java.util.List;
public class Postman implements Observable{ //快递员

    private List<Observer> personList = new ArrayList<>();//保存收件人的信息

    @Override
    public void add(Observer observer) {
        personList.add(observer);
    }

    @Override
    public void remove(Observer observer) {

        personList.remove(observer);
    }

    @Override
    public void notify(String message) {

        for (Observer observer:personList)
        observer.update(message);
    }
}

抽象观察者

public interface Observer { //抽象观察者

    public void update(String message); //更新方法
}

具体观察者

public class Boy implements Observer{

    private String name; //名字

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

    @Override
    public void update(String message) {

        System.out.println(name + ",收到了信息:" + message+",高高兴兴的去取快递...");
    }
}


public class Girl implements Observer{

    private String name;

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

    @Override
    public void update(String message) {

        System.out.println(name+",收到了信息:" + message + "让男朋友去取快递");
    }
}

测试一下:

public class Test {

    public static void main(String[] args){

        Observable postman = new Postman();

       Observer boy1 = new Boy("汤姆");
        Observer boy2 = new Boy("杰瑞");
        Observer girl1 = new Girl("露丝");
        postman.add(boy1);
        postman.add(boy2);
        postman.add(girl1);

        postman.notify("快递到了,请下楼取快递...");
    }
}

运行结果如下:


image.png

实际上jdk中内置了Observer和Observable
下面我们来模拟一下开发技术前线的发布过程:

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

public class Coder implements Observer{

    private String name;

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

    @Override
    public void update(Observable o, Object arg) {
        System.out.println("Hi," + name + "技术博客更新了,内容:" + arg);
    }

    @Override
    public String toString() {
        return "码农:" + name;
    }
}

import java.util.Observable;

public class DevTechFrontier extends Observable{

    public void postNewPublication(String content){

        //标识状态或者内容发生改变
        setChanged();

        notifyObservers(content);
    }
}

public class TestOrginal {

    public static void main(String[] args){

        //被观察者
        DevTechFrontier devTechFrontier = new DevTechFrontier();
        //观察者
        Coder mrSimple = new Coder("mr.simple");
        Coder coder1 = new Coder("coder-1");
        Coder coder2 = new Coder("coder-2");
        Coder coder3 = new Coder("coder-3");

        //将观察者注册到可观察对象的观察者列表中
        devTechFrontier.addObserver(mrSimple);
        devTechFrontier.addObserver(coder1);
        devTechFrontier.addObserver(coder2);
        devTechFrontier.addObserver(coder3);

        devTechFrontier.postNewPublication("新一期的技术周刊发布啦。。。");


    }
}

我们来看一下jdk内置的Observable和Observer源码

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



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); //定义了一个update方法
}


我们在Android源码中,也会用到观察者模式,比如在一个列表中,我们添加了数据后,都会调用adapter.notifyDataSetChanged()
我们进入notifyDataSetChanged方法源码中看一下:

   public final void notifyDataSetChanged() {
            mObservable.notifyChanged();
        }

跟我们的示例代码原理一样,被观察者去通知更新

相关文章

  • 11.9设计模式-观察者模式-详解

    设计模式-观察者模式 观察者模式详解 观察者模式在android中的实际运用 1.观察者模式详解 2.观察者模式在...

  • RxJava基础—观察者模式

    设计模式-观察者模式 观察者模式:观察者模式(有时又被称为发布(publish )-订阅(Subscribe)模式...

  • 前端面试考点之手写系列

    1、观察者模式 观察者模式(基于发布订阅模式) 有观察者,也有被观察者。 观察者需要放到被观察者列表中,被观察者的...

  • RxJava 原理篇

    一、框架思想 观察者模式观察者自下而上注入被观察者被观察者自上而下发射事件观察者模式 装饰器模式自上而下,被观察者...

  • 观察者模式

    观察者模式概念 观察者模式是对象的行为模式,又叫作发布-订阅(publish/subscrible)模式。 观察者...

  • 设计模式-观察者模式

    观察者模式介绍 观察者模式定义 观察者模式(又被称为发布-订阅(Publish/Subscribe)模式,属于行为...

  • 观察者模式

    观察者模式 观察者模式的定义 观察者模式(Observer Pattern)也叫做发布订阅模式(Publish/s...

  • iOS设计模式之观察者模式

    观察者模式 1、什么是观察者模式 观察者模式有时又被称为发布(publish)-订阅(Subscribe)模式、模...

  • 观察者模式和发布订阅模式区别

    观察者模式 所谓观察者模式,其实就是为了实现松耦合(loosely coupled)。 在观察者模式中,观察者需要...

  • RxJava(二)

    一、观察者模式 1.1、传统的观察者模式 1.2、RxJava 的观察者模式 区别传统的观察者模式是一个 Obse...

网友评论

      本文标题:观察者模式

      本文链接:https://www.haomeiwen.com/subject/ffnethtx.html