zoukankan      html  css  js  c++  java
  • 观察者模式

    1、观察者设计模式定义:观察者模式定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。

    2、观察者设计模式的UML类图:

                            

    3、关键字

    • Observable
      即被观察者,也可以被叫做主题(Subject)是被观察的对象。通常有注册方法(register),取消注册方法(remove)和通知方法(notify)。
    • Observer
      即观察者,可以接收到主题的更新。当对某个主题感兴趣的时候需要注册自己,在不需要接收更新时进行注销操作。

    4、代码实现:  

    举一个生活中的例子:比如用户从报社订阅报纸,报社和用户之间是一对多依赖,用户可以在报社订阅(register)报纸,报社可以把最新的报纸发给用户(notify),用户自动收到更新。在用户不需要的时候还可以取消注册(remove)。

    再比如Android中的EventBus,Rxjava的实现都是基于观察者模式的思想。再比如回调函数:Android中对Button的点击监听等等。

    观察者模式可以用来解耦

    5、再说Servlet中的Listener之前, 先说说观察者模式的另一种形态——事件驱动模型。与上面提到的观察者模式的主题角色一样, 事件驱动模型包括事件源, 具体事件, 监听器, 具体监听器。
    Servlet中的Listener就是典型的事件驱动模型。
    JDK中有一套事件驱动的类, 包括一个统一的监听器接口和一个统一的事件源,源码如下:
    /**
     * A tagging interface that all event listener interfaces must extend.
     * @since JDK1.1
     */
    public interface EventListener {
    }
    

      这是一个标志接口, JDK规定所有监听器必须继承这个接口。

    public class EventObject implements java.io.Serializable {
      private static final long serialVersionUID = 5516075349620653480L;
      /**
       * The object on which the Event initially occurred.
       */
      protected transient Object source;
      /**
       * Constructs a prototypical Event.
       *
       * @param  source  The object on which the Event initially occurred.
       * @exception IllegalArgumentException if source is null.
       */
      public EventObject(Object source) {
        if (source == null)
          throw new IllegalArgumentException("null source");
        this.source = source;
      }
      /**
       * The object on which the Event initially occurred.
       *
       * @return  The object on which the Event initially occurred.
       */
      public Object getSource() {
        return source;
      }
      /**
       * Returns a String representation of this EventObject.
       *
       * @return A a String representation of this EventObject.
       */
      public String toString() {
        return getClass().getName() + "[source=" + source + "]";
      }
    }
    

      EvenObject是JDK给我们规定的一个统一的事件源。EvenObject类中定义了一个事件源以及获取事件源的get方法。

  • 相关阅读:
    kafka注册异常
    Android基于XMPP Smack Openfire下学习开发IM(五)连接断开重连
    openfire维持在线状态,监听消息
    openfire ping的smack解决方案(维持在线状态)
    openfire聊天记录插件
    openfire 发送 接受 注册 广播 好友列表 在线状态
    maven仓库中心mirrors配置多个下载中心(执行最快的镜像)
    开发openfire 消息拦截器插件PacketInterceptor
    Openfire注册流程代码分析
    linux centOS6 nexus 开启自动启动
  • 原文地址:https://www.cnblogs.com/swfzzz/p/8534709.html
Copyright © 2011-2022 走看看