Observable in Java

前端 未结 9 1856
别那么骄傲
别那么骄傲 2020-12-14 19:30

I\'m trying to understand the Observer and the Observable.

Here\'s an example that I\'m trying to figure out:

public class IntegerDataBag extends Obs         


        
9条回答
  •  春和景丽
    2020-12-14 20:11

    Let's take a practical example for Observer pattern: Twitter. With Twitter we can follow some other people and read whatever they post in near realtime.

    Every twitter user is observable. You can add yourself as a listener ("Follower") and read his/her posts. Every twitter user will do a "notify Followers" (notifyObservers).

    Here we do the same. The class IntegerDataBag has the capability to notify other classes whenever a value is added to or deleted from it's internal bag. Any instance (that implements Observer) can register itself to an IntegerDataBag and will receive messages through it's callback method (update).

    In short, we do the following:

    1. A observer (listener, IntegerAdder) adds itself to an observable (IntegerDataBag)
    2. Something happens at the observable and the observable notifies its observers
    3. The observable will call the callback methods of all actual observers
    4. The observer now has been notified of the event and can use it

    Hope, this short description helps in understanding this pattern.


    publish/subscribe is a similiar pattern: a publisher is like an observable, a subscriber like an observer. And another practical example: one can subscribe to a newspaper and the publisher will send the paper until you cancel your subscription.

提交回复
热议问题