I'm now learning about the Listener or Observer-Observable design patter, i tried to implement my own class using the supplied Java library Observer
interface and Observable
class.
My Observable
subject is an empty class that extends Observable
.
Here are my two Observer
classes:
public class CatObserver implements Observer {
private String status = "Sleeping...";
@Override
public void update(Observable o, Object arg) {
System.out.println("Updated!");
this.status = "Awake!";
}
public void getStatus(){
System.out.println(status);
}
}
public class DogObserver implements Observer {
private String status = "Sleeping...";
@Override
public void update(Observable o, Object arg) {
this.status = "Awake!";
}
public void getStatus(){
System.out.println(status);
}
}
Here is my main
program:
public class Listener {
public static void main(String[] args) {
AnimalSubject subject = new AnimalSubject();
CatObserver mitsy = new CatObserver();
DogObserver ozil = new DogObserver();
mitsy.getStatus();
ozil.getStatus();
subject.addObserver(mitsy);
subject.addObserver(ozil);
synchronized (subject){
subject.notifyAll();
}
mitsy.getStatus();
ozil.getStatus();
}
My output is 4 lines of "Sleeping...", when it should be 2 lines of "Sleeping..." and 2 lines of "Awake!".
When debugging it won't even go into the update()
functions.
What am I doing wrong here?
Aucun commentaire:
Enregistrer un commentaire