SDSU CS535 Object-Oriented Programming & Design
Fall Semester, 1996
Doc 26 AWT Adding Observers

[To Lecture Notes Index]
San Diego State University -- This page last updated Nov 21, 1996
----------

Contents of Doc 26 AWT Adding Observers

  1. Adding the Same Observer Twice?
  2. Deleting Observers

Doc 26 AWT Adding Observers Slide # 1Listen Here!
Simple Example
class SimpleCounter extends Observable{
   public int count = 0;
   
   public void increase() { 
      count++; 
      setChanged();
      notifyObservers(); 
   }
}
   
class SimpleObserver implements Observer  {
   String id;
   public SimpleObserver( String id ) {
      this.id = id ;
   }

   public void update( Observable sender, Object message ) {
      System.out.println( "From " + id + " New value " + 
         ((SimpleCounter) sender).count );
   }
}
   
class ObserveTest {
   public  static  void  main( String  args[] ) {
      SimpleCounter test = new SimpleCounter();
      SimpleObserver a = new SimpleObserver( "a" );
      test.addObserver( a);
      test.addObserver( new SimpleObserver( "b" ) );
      test.increase();
      test.addObserver( new SimpleObserver( "c" ) );
      test.increase();
      }
   }


Doc 26 AWT Adding Observers Slide # 2Listen Here!
Running the Example
class ObserveTest {
   public  static  void  main( String  args[] ) {
      SimpleCounter test = new SimpleCounter();
      SimpleObserver a = new SimpleObserver( "a" );
      test.addObserver( a);
      test.addObserver( new SimpleObserver( "b" ) );
      test.increase();
      test.addObserver( new SimpleObserver( "c" ) );
      test.increase();
      }
   }
Output
From b New value 1
From a New value 1
From c New value 2
From b New value 2
From a New value 2

Doc 26 AWT Adding Observers Slide # 3Listen Here!

Adding the Same Observer Twice?

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

      SimpleCounter test = new SimpleCounter();
      SimpleObserver a = new SimpleObserver( "a" );

      test.addObserver( a);
      test.addObserver( a );

      test.increase();

      test.addObserver( a );
      test.increase();
      }
   }
Output
From a New value 1
From a New value 2

Doc 26 AWT Adding Observers Slide # 4Listen Here!

Deleting Observers

class ObserveTest {
   public  static  void  main( String  args[] ) {
      SimpleCounter test = new SimpleCounter();
      SimpleObserver a = new SimpleObserver( "a" );
      SimpleObserver b = new SimpleObserver( "b" );

      test.addObserver( a);
      test.addObserver( b);
      test.increase();

      System.out.println( "Delete a" );
      test.deleteObserver( a );
      test.increase();

      System.out.println( "Delete a again" );
      test.deleteObserver( a );
      test.increase();

      System.out.println( "Delete all" );
      test.deleteObservers( );
      test.increase();
      }
   }
Output

From b New value 1
From a New value 1
Delete a
From b New value 2
Delete a again
From b New value 3
Delete all


----------