The Observer Pattern defines a one-to-many dependency between
objects so that when one object changes state, all of its
dependents are notified and updated automatically.
Class Diagram
Subject Role
public abstract class Subject {
private Vector<Observer> obsVector = new Vector<Observer>();
public void addObserver(Observer o) {
this.obsVector.add(o);
}
public void delObserverr(Observer o) {
this.obsVector.remove(o);
}
public void notifyObservers() {
for (Observer o:this.obsVector) {
o.update();
}
}
}
ConcreteSubject Role
public class ConcreteSubject extends Subject {
public void doSomething() {
//do something
notifyObserver();
}
}
Observer Role
public interface Observer {
public void update();
}
ConcreteObserver Role
public class ConcreteObserver implements Observer {
pulic void update() {
system.put.println("received notification, do somthing");
}
}
Client Role
public class Client {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();
Observer obs = new ConcreteObserver();
subject.addObserver(obs);
subject.doSomething();
}
}