Created
February 17, 2018 03:37
-
-
Save jigewxy/4eeaa70cfbe2f01b21da82d5b8e6991c to your computer and use it in GitHub Desktop.
Observable Class and Observer Interface
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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