Java Very Simple Observer Pattern Example


Java Very Simple Observer Pattern Example


My attempt to demonstrate the observer pattern..

Java Example



----------------------------CODE-----------------------------------


//AUTHOR : THE JAVA GEORDIE
//
//SIMPLEST EXAMPLE I COULD THINK
//OF TO DEMONSTATE THE OBSERVER PATTERN

class start
{
public static void main(String args[])
{

   ///instantiate the watcher (observer) and the 
   // being watched(observed) class 
 
watcher watch = new watcher();
beWatched bwatch = new beWatched();


   //add a watcher to the being watched (observed) class
bwatch.addObserver(watch);

// make the being watched (observed) class
// do something....
bwatch.setStuff();
}
}

-----------------------------------------------------


//AUTHOR : THE JAVA GEORDIE
//
//THIS CLASS EXTENDS OBSERVABLE TO IS BEING WATCHED


import java.util.Observable;

class beWatched extends Observable
{
public void setStuff()
{
// NOTIFY THE OTHER WATCHERS SOMETHING HAS HAPPEND.
// IN THIS CASE NOT MUCH
setChanged();
notifyObservers();
}

}
-------------------------------------------------


//AUTHOR : THE JAVA GEORDIE
//
// THIS IS A WATCHER (OBSERVER) CLASS
// THAT IMPLEMENTS THE OBSERVER INTERFACE

import java.util.Observer;
import java.util.Observable;

class watcher implements Observer
{
// IF SOMETHING HAPPENS TO THE WATCHED CLASS
// DO SOMETHING
/////////////////////////////////////////////

public void update(Observable obj, Object arg)
{
System.out.println("Something changed!");
}
}

---------------OUTPUT------------------

Something changed!



1 comment: