Java:
I am aware of the java.util.Observable, but I wanted to demonstrate an manual implementation.
interface Subject {
void addObserver(Observer o);
void removeObserver(Observer o);
void notifyObserver(Observer o);
}
class RealSubject implements Subject {
private String property;
private Vector<Observer> observers;
RealSubject() {
observers = new Vector<Observer>();
property = "value";
}
public void addObserver(Observer o) {
observers.add(o);
}
public void removeObserver(Observer o) {
if (observers.indexOf(o) >=0 ) observers.remove(o);
}
public void notifyObserver(Observer o) {
for (Observer obs : observers) {
obs.update(property);
}
}
public String getProperty() {
return property;
}
}
interface Observer {
void update(String property);
}
class RealObserver implements Observer {
private String property;
private Subject s;
RealObserver(Subject s) {
this.s = s;
s.addObserver(this);
}
public void update(String property) {
this.property = property;
}
}