开发者

Adding Listeners at runtime? - Java MVC

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 listene开发者_Go百科r 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?


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.

Adding Listeners at runtime? - Java MVC


(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.

Adding Listeners at runtime? - Java MVC


(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.


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


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜