Implementing a Simple Event Notifier - Java Design Pattern

Java examples for Design Pattern:Observer Pattern

Description

Implementing a Simple Event Notifier

Demo Code

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

public class Main {
  public static void main(String[] argv) {
    // Create the model
    MyModel model = new MyModel();

    // Register for events
    model.addObserver(new Observer() {
      public void update(Observable o, Object arg) {
      }/*from  w  ww  .  ja  va2 s . c  o m*/
    });

    // Indicate that the model has changed
    model.setChanged();

    // Fire an event to all the views
    Object arg = "some information about the event";
    model.notifyObservers(arg);
  }
}// Declare the model

class MyModel extends Observable {
  // The setChanged() protected method must overridden to make it public
  public synchronized void setChanged() {
    super.setChanged();
  }
}

Related Tutorials