Observable in Java

前端 未结 9 1870
别那么骄傲
别那么骄傲 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 19:55

    The bag.addObserver() can be made only because IntegerDataBag extends Observable?

    Yes, the addObserver method is implemented in Observable.

    Where is this observer being add to? what being created and where?

    The observer is being added to a list of observers which is declared in Observable as private, so it is not visible in your subclass.

    What is the different between setChanged() and notifyObservers()?

    When you call notifyObservers() without first calling setChanged(), no notifications take place.

    I don't understand the update method- what does args stands for? and why do I need to check that o==bag, why would I update another observable?

    One Observer can watch multiple Observables. By examining the first parameter of the update method, you can figure out which observer is notifying you about something.

    Why should I need this observer anyway?

    Any time you want a class to send events to other classes but you don't want a direct dependency from that class on its observers.

提交回复
热议问题