Question

My model in my MVC pattern, generates components at runtime and gives them to the View to be displayed on the screen through update() method (you know, model is the observable and the view is the observer). But I also need to add listeners to these components, and the controller has the listener methods (because they say the MVC pattern is like this) and it's not involved in this update process. So I can't add the listeners at runtime, but only in the controller's constructor at startup.

I've got an idea, that is making the controller the observer and then giving the data to the view, as well as adding the listeners. Do you think this would be OK?

Was it helpful?

Solution

Yup, making the controller your model observer to allow it to update the view would definitively fit, to my mind, in MVC orthodoxy.

OTHER TIPS

I think that you may have some wires crossed.

  1. The model is observable (check!)
  2. The view is observing the model (check!)
  3. The controller is bound to the view (TODO!)

The #3 means that the user interactions from the view are supposed to invoke a registered listener in the controller class, which then updates the model state.

This is the 'classic' Swing MVC. alt text
(source: sun.com)

A 'modified' Swing MVC (which was recommended by some other answers on this question), has the controller play the role of Mediator.

In this design, the view calls an appropriate method on the controller when the user does actions. Then, the controller accesses the model (maybe updating it). Finally, if the model is altered, it notifies interested listeners (in this case, the controller).

This is a 'modified' MVC. alt text
(source: sun.com)

The second design ('modified' MVC) allows very obvious decoupling of the model and view.

For more info, check out this article about Java Swing MVC. It's fantastic.

In swing for example the controller/action listener is the observer for the view (buttons etc) and on invoking the buttons (i.e, when view changes) controller kicks in and interacts with the model and updates the view again (with new model changes)

So what you have suggested in the end does make sense to me :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top