Search code examples
javaobserver-pattern

addObserver() method, of observer pattern and object variable lifecycle/scope, Java


when I use the method .addObserver() for example:

  class ExampleOne implements Observer {

  class ExampleTwo extends Observable {


  ExampleOne one = new ExampleOne();

  ExampleTwo two = new ExampleTwo();

  two.addObserver(one)

in this case, is the connection between instance objects "two" and "one" or the class.class like a static situation, it looks to me like instance, but not sure, if this is a connection between observer and the observed then what happens if either "one" or "two" is garbage collected or goes out of scope? does that destroy the observer setup.

example of this is when a server receives a String message from the client, and the observer is used to notify when a new text message has arrived. if one of the instance variables goes out of scope and is garbage collected then there will be no more notification when messages arrive because the system will be broken. is this correct?


Solution

  • Observable has a vector which holds the reference to all the observers that have been registered using the addObserver() method. So even if the observer goes out of scope the reference to it is still present in the observable and will not be garbage collected.

    To garbage collect it call the removeObserver and then it will be garbage collected.

    If Observable goes out of scope then yes, no notifications would be sent now to the observers. And the Observers can be garbage collected.

    in this case, is the connection between instance objects "two" and "one" or the class.class like a static situation

    Yes everything is happening on instances and no statics are involved here.