I have a problem trying to implement the Observer-pattern into my MVC solution for a simple program, however I can't get the observer to notify "update" like it should.
These are the relevant parts of the code, there is a third class(Controller) which calls the "spelarNamn" function. I have tested the "spelarNamn" function and I know the program enters it, the only problem is that it never enters update function in View.
public class Model extends Observable {
private String titel;
public static void main(String[]args){
Model model = new Model();
Controller controller = new Controller(model);
View view = new View(model, controller);
model.addObserver(view);
}
public void spelarNamn(String s1, String s2){
titel = s1 + " VS " + s2;
this.setChanged();
this.notifyObservers();
}
}
public class View implements Observer {
public void update(Observable o, Object x){
System.out.println("hi");
}
}
The controller is calling the spelarNamn() method before the Observer is added. Move model.addObserver(view) up before the controller call.