热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

观察者模式在Android开发场景中运用之通过Java源码分析(一)

源码中,起关键性作用的就是vector和changed,在observable实例化的时候,就初始化了一个空的vector,可以通过vector添加和移除vector操作后,当ob

对于观察者,很多开发者并不陌生,在日常开发过程中,这也是一个非常常见的设计模式,尤其是Android小伙伴,很多人都知道broadcast就是一个典型的观察者模式,还有最近很火的rxjava,响应式编程中,观察者模式扮演着一个很重要的角色,但观察者模式具体是怎么样运转的,部分小伙伴就有点模糊了。

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

技术分享

DevilsSubject.java

/**
 * 
 * created by zm on 2016-5-28
 * 继承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()获取是否发生改变,这里我们统一设置成改变,以便测试
        this.setChanged();
        this.notifyObservers(assault);
    }
}

VillagerObserver.java

/**
 * 
 * created by zm on 2016-5-28
 * 
 * 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("前方有一坨鬼子来了");
        devilsSubject.setAssault("鬼子见阎王了,在来村的路上就被村民手撕了");
        //返回 Observable 对象的观察者数目
        System.out.println(devilsSubject.countObservers());
        System.out.println("................");
        devilsSubject.deleteObserver(yes);
        devilsSubject.setAssault("鬼子来了");
        System.out.println(devilsSubject.countObservers());
    }
}

运行的结果:

前方有一坨鬼子来了
前方有一坨鬼子来了
鬼子见阎王了,在来村的路上就被村民手撕了
鬼子见阎王了,在来村的路上就被村民手撕了
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.
 * 

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

* 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. *

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

* When an observable object is newly created, its set of observers is * empty. Two observers are considered the same if and only if the * equals 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 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 null 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 * hasChanged method, then notify all of its observers * and then call the clearChanged method to * indicate that this object has no longer changed. *

* Each observer has its update method called with two * arguments: this observable object and null. In other * words, this method is equivalent to: *

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

* Each observer has its update method called with two * arguments: this observable object and the arg 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 Observable object as having been changed; the * hasChanged method will now return true. */ 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 hasChanged method will now return false. * This method is called automatically by the * notifyObservers 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 true if and only if the setChanged * method has been called more recently than the * clearChanged method on this object; * false otherwise. * @see java.util.Observable#clearChanged() * @see java.util.Observable#setChanged() */ public synchronized boolean hasChanged() { return changed; } /** * Returns the number of observers of this Observable object. * * @return the number of observers of this object. */ public synchronized int countObservers() { return obs.size(); } }

再附上Observable的api
技术分享

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

源码中,起关键性作用的就是vector和changed,在observable实例化的时候,就初始化了一个空的vector,可以通过vector添加和移除vector操作后,当observable发生改变时,通过changed去判断是否通知,在我们的上述示例代码中使用setChanged(),主要是因为第一次加入的时候,不会去调用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 Observer 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 Observable object‘s
     * notifyObservers method to have all the object‘s
     * observers notified of the change.
     *
     * @param   o     the observable object.
     * @param   arg   an argument passed to the notifyObservers
     *                 method.
     */
    void update(Observable o, Object arg);
}

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

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

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

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

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

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

技术分享

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

观察者模式在Android开发场景中运用之通过Java源码分析(一)


推荐阅读
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 猜字母游戏
    猜字母游戏猜字母游戏——设计数据结构猜字母游戏——设计程序结构猜字母游戏——实现字母生成方法猜字母游戏——实现字母检测方法猜字母游戏——实现主方法1猜字母游戏——设计数据结构1.1 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 动态规划算法的基本步骤及最长递增子序列问题详解
    本文详细介绍了动态规划算法的基本步骤,包括划分阶段、选择状态、决策和状态转移方程,并以最长递增子序列问题为例进行了详细解析。动态规划算法的有效性依赖于问题本身所具有的最优子结构性质和子问题重叠性质。通过将子问题的解保存在一个表中,在以后尽可能多地利用这些子问题的解,从而提高算法的效率。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • Java验证码——kaptcha的使用配置及样式
    本文介绍了如何使用kaptcha库来实现Java验证码的配置和样式设置,包括pom.xml的依赖配置和web.xml中servlet的配置。 ... [详细]
  • Redis底层数据结构之压缩列表的介绍及实现原理
    本文介绍了Redis底层数据结构之压缩列表的概念、实现原理以及使用场景。压缩列表是Redis为了节约内存而开发的一种顺序数据结构,由特殊编码的连续内存块组成。文章详细解释了压缩列表的构成和各个属性的含义,以及如何通过指针来计算表尾节点的地址。压缩列表适用于列表键和哈希键中只包含少量小整数值和短字符串的情况。通过使用压缩列表,可以有效减少内存占用,提升Redis的性能。 ... [详细]
author-avatar
m71051588
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有