美文网首页
03 - 观察者模式

03 - 观察者模式

作者: shalk | 来源:发表于2018-06-05 10:54 被阅读0次

定义:

一个对象进行某些操作时,主动通知另外一个对象。属于行为型设计模式。

场景:

例如有多个天气公告牌,公告牌展示的数据不同,格式不同,数据来源相同。
此时,数据源是主题,即被观察者, 天气公告牌是观察者。

类图如下:


image.png

notifyObservers一般 是对每一个Observer 调用update接口

这样WeatherData 和 WeatherDisplay 解耦,而且Dsiplay可以扩展。

JDK的实现

JDK中提供了观察者模式的接口,分别是Observable和Observer

Observable 是一个具体的类,直接继承就可以使用,提供了更多的方法。
方法清单:

addObserver   //添加
deleteObserver //删除
notifyObservers() //通知
notifyObservers(Object args)  // 带参数通知
deleteObservers  // 删除所有

//对changed标志位的控制
setChanged  
clearChanged
hasChanged
countObservers

部分源码

public class Observable {
    private boolean changed = false;
    private Vector<Observer> obs;

可以看到这个实现,比之前的例子多了标志位的控制,避免没有改变的情况下反复通知,而且可以选择通知时带什么参数,并且内部实现时,做了加锁同步,尽管Vertor是线程安全的,但是有大量的复合,遍历操作。 需要避免竞态。

很不错?缺点?

  1. Observable是具体的类,导致有的对象如果已经有父类,就无法继承Observable
  2. Vector是despertate的容器。

还有更多的缺点,直接导致JDK9中,Observable类被desperate。
见:https://docs.oracle.com/javase/9/docs/api/java/util/Observable.html

This class and the Observer interface have been deprecated. The event model supported by Observer and Observable is quite limited, the order of notifications delivered byObservable is unspecified, and state changes are not in one-for-one correspondence with notifications. For a richer event model, consider using the java.beans package. For reliable and ordered messaging among threads, consider using one of the concurrent data structures in the java.util.concurrent package. For reactive streams style programming, see the Flow API

这里做了三个推荐

  1. 丰富的事件模型,java beans
  2. 并发数据结构,java.util.concurrent
  3. 响应式流式风格,考虑Flow API

END

相关文章

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

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

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

    2019-03-06-12:31 午饭吃完啦~ 观察者模式和发布订阅模式最大的区别就是发布订阅模式有个事件 调度中...

  • RxJava基础—观察者模式

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

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

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

  • RxJava 原理篇

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

  • 观察者模式

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

  • 设计模式-观察者模式

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

  • 观察者模式

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

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

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

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

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

网友评论

      本文标题:03 - 观察者模式

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