class Signal extends Observable {
void setData(byte[] lbData){
setChanged(); // Positionne son indicateur de changement
notifyObservers(); // (1) notification
}
}
class JPanelSignal extends JPanel implements Observer {
void init(Signal lSigAObserver) {
lSigAObserver.addObserver(this); // (2) ajout d'observateur
}
void update(Observable observable, Object objectConcerne) {
repaint(); // (3) traitement de l'observation
}
}
// Java Observer pattern (Simple version)
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}
public interface Observer {
public void update(int value);
}
public class SimpleSubject implements Subject {
private List<Observer> observers;
private int value = 0;
public SimpleSubject() {observers = new ArrayList<Observer>();}
public void registerObserver(Observer o) {observers.add(o);}
public void removeObserver(Observer o) {observers.remove(o);}
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(value);
}
}
public void setValue(int value) {
this.value = value;
notifyObservers();
}
}
public class SimpleObserver implements Observer {
private int value;
private Subject simpleSubject; // who to subscribe
public SimpleObserver(Subject simpleSubject) {
this.simpleSubject = simpleSubject;
simpleSubject.registerObserver(this);
}
public void update(int value) {
this.value = value;
display();
}
public void display() {System.out.println("Value: " + value);}
}
public class Example {
public static void main(String[] args) {
SimpleSubject simpleSubject = new SimpleSubject();
SimpleObserver simpleObserver = new SimpleObserver(simpleSubject);
simpleSubject.setValue(80); // output: 80
simpleSubject.removeObserver(simpleObserver);
}
}