| 
 import java.util.Vector; 
abstract 
public 
class Subject { 
  private 
  Vector observers; 
  //-------------------- 
  protected 
  Subject() { 
    observers = new Vector(); 
  } 
  //-------------------- 
  public 
  synchronized 
  void addObserver(Observer o) { 
    observers.addElement(o); 
    o.setSubject(this);                 // link back 
  } 
  //-------------------- 
  public 
  synchronized 
  void removeObserver(Observer o) { 
    observers.removeElement(o); 
    o.setSubject(null);                 // remove link back 
  } 
  //-------------------- 
  public 
  synchronized 
  void notifyObservers() { 
    Vector o = (Vector)(observers.clone()); 
    for ( int i = 0, max = o.size(); 
          i < max; 
          ++i ) { 
      ((Observer)(o.elementAt(i))).update(); 
    } 
  } 
} 
 | 
    
| 
 abstract 
public 
class Observer { 
  protected 
  Subject s; 
  public 
  void setSubject(Subject s) { 
    this.s = s; 
  } 
  abstract 
  public 
  void update(); 
} 
 | 
    
| 
 public 
class Clock extends Subject { 
  private 
  int seconds; 
  //-------------------- 
  public 
  int getTime() { 
    return 
      seconds; 
  } 
  //-------------------- 
  public 
  int getMinutes() { 
    return 
      seconds / 60; 
  } 
  //-------------------- 
  public 
  void setTime(int seconds) { 
    this.seconds = seconds; 
    notifyObservers();          // state changed 
  } 
  //-------------------- 
  public 
  void tick() { 
    ++seconds; 
    notifyObservers();          // state changed 
  } 
} 
 | 
    
| 
 public 
class ClockObserver1 extends Observer { 
  public 
  void update() { 
    Clock c = (Clock)s;         // downcast !!! 
    System.out.println("time in seconds is " + c.getTime()); 
  } 
} 
 | 
    
| 
 public 
class ClockObserver2 extends Observer { 
  private 
  int minutes = -1;             // observer state 
  //-------------------- 
  public 
  void update() { 
    Clock c = (Clock)s;         // downcast !!! 
    int minutes = c.getMinutes(); 
    // output only if observer state changes 
    if ( minutes != this.minutes ) { 
      this.minutes = minutes; 
      System.out.println("time in minutes is " + minutes); 
    } 
  } 
} 
 | 
    
| Letzte Änderung: 13.04.2012 | © Prof. Dr. Uwe Schmidt |