Skip to content

Instantly share code, notes, and snippets.

@jigewxy
Created February 17, 2018 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jigewxy/4eeaa70cfbe2f01b21da82d5b8e6991c to your computer and use it in GitHub Desktop.
Save jigewxy/4eeaa70cfbe2f01b21da82d5b8e6991c to your computer and use it in GitHub Desktop.
Observable Class and Observer Interface
package com.company;
import java.util.Observable;
import java.util.Observer;
class ObservableObj extends Observable{
private int watched;
ObservableObj (int watched){
this.watched = watched;
}
public void setWatched(int value){
System.out.println("set new value as "+value );
if(this.watched!=value) {
this.watched = value;
setChanged();
System.out.println(hasChanged());
notifyObservers(value);
}
else
System.out.println("Nothing has changed");
//after notification, it will reset the changed state, or else it will keep notify;
}
}
class ObserverObj implements Observer{
public void update (Observable o, Object arg)
{
System.out.println("observer has been updated to "+ arg);
}
}
public class ObserverDemo {
public static void main(String[] args){
ObservableObj notifier = new ObservableObj(1);
ObserverObj subscriber = new ObserverObj();
notifier.addObserver(subscriber);
notifier.setWatched(1);
}
}
/*
* 1. create ObservableObj extends java.util.Observable class
* - Add trigger function: setWatched(value), it does update the state and notify the observer.
* remember to setChanged() before notifyObservers(), or else it won't work.
* 2. create ObserverObj implements java.util.Observer interface
* 3. add observer to ObservableObj using notifier.addObserver() method
* 4. invoke the trigger function in notifier.
*
* */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment