Can Model Observe View?
I am developing an application in Java, in my GUI I have several JPanels
with a lot of settings on them, this would be the View开发者_运维百科. There is only one Model in the background of these several JPanels
. Normally, I would Observe the Model from the JPanels
.
I was just wondering, is it good practice to Observe View from the Model? Because, the user changes the View, and this change must effect my Model. Or am I missing some important principle here? Thank you for your help..
I think its great you are questioning this.
What part you are missing that could help is a Controller.
Check out http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller for an example.
Basically a controller is the mediator between a model and a view. It "Controls" the application. The only thing that your view should know about is the data that is being passed to it and how to display it. The only thing your Model should know about is data. The Controller ties these two together and contains the business logic that acts on the data and prepares it to pass to the view.
What you get from using this design is a loosley coupled and easy to test application. It really is elegant IMHO.
Cheers,
Mike
That would create unnecessary binding between the model and the view. But also think about an infinite cycle that you could get into.
What if the model was also updated by something other than a view, perhaps a web service? Then a change in the model through the web service will result a change in the view as the view would be observing the model. And also a change in the view will trigger a change in the model as the model is observing the view too. See the recursion here? It's not too difficult to bypass it, but will result in a really bad and unmaintainable design.
To tie your model and view together, one solution as has already been proposed is to add a Controller so that you have the full set of Model-View-Controller components implemented. This introduces a very tight coupling between all three components, which from a unit-test perspective is not really desirable.
An alternative would be to consider the Model-View-Presenter pattern. The Presenter would be the intermediary between the Model and the View, and would update the Model based on any input from the View, and would also be responsible for updating the view based on any changes in the Model. For your unit-tests, you would then be able to substitute a mock-View to test the Model, or a mock-Model to test the view (or mock both to test only the Presenter).
精彩评论