Observable in Java

前端 未结 9 1860
别那么骄傲
别那么骄傲 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:05

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

    Correct, Observable is a class that has the addObserver() method.

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

    The Observer class contains a List or Vector (in the JDK source) of Observable objects.

    private Vector obs;
    

    That's where it's stored.

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

    The setChanged() just marks the Observable is changed. The notifyObservers() just calls the all observers it has on the list to update() (passing a changed object to the Observer) only if the setChanged is set to true.

    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?

    The update() method tells the Observer that it needs to update based on the changed obj it receives. This is called by the notifyObservers() from Observable.

    Why should I need this observer anyway?

    To create a Listener for event driven scenario, i.e. if you want to be informed in the change of your observable objects, then Observer is needed.

    Read: GoF - Observer pattern.

提交回复
热议问题