Re: Design Question for Model and View
Jason Cavett wrote On 05/30/07 15:40,:
I have a question about a design for a model/view and communication
between the two.
I have a model (MainModel) that holds a Collection of project
objects. It keeps track of which projects are open, what the current
project is, it initializes projects and saves projects. I have a view
to this model which provides me access to these various tasks. (The
MainModel can have multiple projects open at a time. These projects
are shown in the view.) The view is an Observer of the MainModel.
This all works great.
The problem I run into (sort of a problem - I can easily hack around
it, but I'm wondering if there's a better way) is that it can be tough
getting information from the user when I need to accomplish a goal.
For example, if I'm closing an open project, the user selects "close"
in the MainView. Here is how I think it should happen - if there's a
better way, please let me know.
1. The user selects "Close Project"
2. The view (which knows about the model) calls "model.close()"
3. The model checks to see if the project is saved. If it's not
saved, the model notifies that view that it needs to ask the user if
they want to save before they close.
4. [TRICKY PART] - The view pops up a JOptionPane and asks the user if
they want to save. The user selects "Yes" The view sets a flag in
the main model notifying that it should save.
5. The model continues, sees the flag has been set to "true" and
saves, then proceeds to close the project.
Is this a good way to go about it? It just seems to me that there
could be a lot of flags floating about if I start doing more within
the MainModel.
There are a lot of ways to approach this. Since your
model apparently knows that it has been changed since last
being saved, it could publish that knowledge. The view
could call model.hasUnsavedChanges() to decide whether it
should get the user's permission before calling model.close().
A variant of the above is for the model to maintain a
counter that increments each time a change is made, and to
publish that counter via model.getVersion(). This lets a
single model be seen by multiple views, each (perhaps) with
its own backing store and its own notion of when things
were last current.
Yet another scheme is to use model.closeIfUnchanged()
and model.closeUnconditionally(). (model.close(boolean)
seems less mnemonic.)
--
Eric.Sosman@sun.com