Java Reference
In-Depth Information
controller.addFunds(Double.parseDouble(add.getText()));
}
});
this.add(funds);
this.add(add);
this.add(addButton);
}
public void updateView(double funds) {
this.funds.setText("Your funds: "+funds);
this.add.setText("");
}
public void setController(AccountController controller) {
this.controller = controller;
}
}
You pat yourself on the back. Well done, the view can now call actions in the controller, which
modifies its models and sends back updates to the view.
Still, you can't help but feel there's something missing . . . Most beginner programmers who want
to decouple models and UI will end up with a solution resembling something you've just seen.
Although the model is now completely unaware of the user interface that might exist (good!), the
problem still remains that the controller is calling methods in the view and the view is calling meth-
ods in the controller, creating a problem where both need to be explicitly aware of one another.
Luckily, thanks to the observer pattern, there is a way to improve this situation. The basic idea is
this: controllers will act as listeners in that they will be notified by the view and then can manipulate
their models. The views will also act as listeners; they will be notified by the models but will not be
able to manipulate them directly. The models finally act as subjects that notify interested parties,
including the listening views.
One aspect of this idea has already been implemented, in a way. That is, the setController method
basically registers the controller as a listener in the view. However, there is a smarter way to do this.
Since you need to listen for UI events coming from the view, why not define the controller as an UI
listener? Second, the controller is now allowed to call methods in the view, serving as an intermedia-
tor between the data stored in the models and how it is represented in the views. A better way to do
this is to change your model to allow listeners.
So, start again with the Account class. You need to add the ability to notify view listeners. There are
several ways to do this:
A registerView method that just sets a single view listener.
A hand‐rolled listener solution that keeps a list of views.
A hand‐rolled listener solution that keeps a list of objects implementing a self‐made
AccountListener interface.
Using the built‐in Observable and Observer class and interface.
Search WWH ::




Custom Search