美文网首页Java设计模式
设计模式之观察者模式(Observer Pattern)

设计模式之观察者模式(Observer Pattern)

作者: 杨斌_1024 | 来源:发表于2020-05-11 23:39 被阅读0次

    概述

    In the observer pattern, observer objects subscribe to an observable object and  to be notified every time ,when the observable changes its data.

    观察者模式是指观察者(多个)对一个目标进行观测,当目标对象被修改时,所有的观察者将会收到通知。观察者模式有两种广播方法push和pull,push是目标对象push到观察者,pull是观察者对象主动pull目标对象的数据。

    通俗一点的说法就是,目标对象持有众多观察者的引用,当目标对象被修改时,会逐一调用观察者对象的方法。

    Pre or Review Knowledge

    ArrayList介绍

    Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

      List list = Collections.synchronizedList(new ArrayList(...));

    Vector介绍

    Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.

    手写观察者模式(Pull)

    观察者模式

    DataSource对象是被观测的对象,也就是目标对象,是Observable对象。它持有观察者Observer的引用,当Observable对象有数据被修改时,会调用观察者Observer的方法用来广播通知。

    DataSource类(Observable)

    观察者对象当接收到广播之后,主动pull目标对象的数据。

    View类(Observer) 测试结果

    java中的观察者模式(push)

    push是目标对象push到观察者

    JavaObservable类(Observable) JavaObserver类(Observer) 测试结果

    java中存在java.util.Observable(Class); java.util.Observer(interface);这两个类可以支持观察者模式,并支持线程同步。可以参看源码。

    本文代码GitHub地址

    参考代码

    相关文章

      网友评论

        本文标题:设计模式之观察者模式(Observer Pattern)

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