wood burning stoves*
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes Confused with MVC Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "Confused with MVC" Watch "Confused with MVC" New topic
Author

Confused with MVC

Padmaja Prasad
Ranch Hand

Joined: Nov 14, 2001
Posts: 76
Hi,
I wish to use MVC pattern in my client side GUI design. I am little bit confused in understanding 'what the model is??'
As per my design, at the client side, I have the following classes:
1) DataClient--> which has the same public method as Data and delegates all method calls to either RemoteData or LocalData.
2) FBNController--> access data from the DataClient to implement business methods such as searchFlight(), bookFlight(), setComboBox(), setTableHeader(), setTableData(),etc. These methods updates (and returns) either the FBMTableModel or FBNComboBoxModel.
3) FBNTableModel extends AbstractTableModel
& FBNComboBoxModel extends DefaultComboBoxModel
4) MainWindow --> consists of JPanels, such as SearchPanel, ViewPanel & BookPanel.
ComboBoxes in searchPanel utilizes FBNComboBoxModel to dispaly combobox for search items & ViewPanel's JTable uses FBNTableModel to display table data.
I am very sure that the Controller is FBNController & view is MainWindow. My question is what is the model here? DataClient or TableModel & ComboBoxModel??
Thanks
Padmaja
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937

2) FBNController--> access data from the DataClient to implement business methods such as searchFlight(), bookFlight(), setComboBox(), setTableHeader(), setTableData(),etc. These methods updates (and returns) either the FBMTableModel or FBNComboBoxModel.

Oh, my favorite subject.
The implementation of business methods such as searchFlight() and bookFlight() belongs to the Model, -- that's exactly what Model is for, -- to model the business.
The methods setComboBox() and setTableHeader() belong to the View where the combobox and JTable are displayed, -- this is exactly what the View is for, -- to render the data. Neither Model nor Controller should call these methods, and neither Model nor Controller should even know how the data is rendered. For the same reason, neither Model nor Controller should return something like FBMTableModel or FBNComboBoxModel.
If you understand the following, you would be able to design your MVC so that each part in MVC has a well defined set of responsibilities:
Model -- encapsulates business logic and holds the application "state". When the application state changes, the model notifies the registered views about the change.
View -- renders the data. May receive the notifications from the Model and update itself. May use the state query methods of the model to update itself. Acts as a Model listener.
Controller -- listens for user actions and maps these actians into businees methods (i.e. invokes the business methods in the Model)
The entire motivation of MVC is to break the complexity of the application into several coherent, loosely coupled pieces. If your MVC design is good, you can change (or completely replace) one part without affecting the other parts in your MVC or anywhere else in your application.
Eugene.
Max Habibi
town drunk
( and author)
Sheriff

Joined: Jun 27, 2002
Posts: 4118
Or to put it another way. Imagine that you're in a restaurant, and you're looking over the menu. The data that's actually on the menu is the model. The menu itself: the plastic, etc., is the view. The waiter who takes your order is the controller. This entire framework´┐Żs job is to protect you from having to deal with the chef directly.
M, author
The Sun Certified Java Developer Exam with J2SE 1.4


Java Regular Expressions
Padmaja Prasad
Ranch Hand

Joined: Nov 14, 2001
Posts: 76
Thank you guys..
Originally posted by Eugene Kononov:
[QB]
Oh, my favorite subject.
The implementation of business methods such as searchFlight() and bookFlight() belongs to the Model, -- that's exactly what Model is for, -- to model the business.

Will it it be ok if I implement the business methods in the DataClient class??

The methods setComboBox() and setTableHeader() belong to the View where the combobox and JTable are displayed, -- this is exactly what the View is for, -- to render the data. Neither Model nor Controller should call these methods, and neither Model nor Controller should even know how the data is rendered. For the same reason, neither Model nor Controller should return something like FBMTableModel or FBNComboBoxModel.

Actually my setComboBox() method of the FBNController fetches the data values (like origin airport codes, etc..that are to be displayed) from the DB & updates the ComboBoxModel. The view calls this method to create ComboBoxes.
Similarly, setTableHeader() sets the Header Values of the TableModel. View calls this method to dispaly the data in a JTable.
I put all these methods in Controller because the view does not know about the underlying data: only the controller knows...

If you understand the following, you would be able to design your MVC so that each part in MVC has a well defined set of responsibilities:
Model -- encapsulates business logic and holds the application "state". When the application state changes, the model notifies the registered views about the change.
View -- renders the data. May receive the notifications from the Model and update itself. May use the state query methods of the model to update itself. Acts as a Model listener.
Controller -- listens for user actions and maps these actians into businees methods (i.e. invokes the business methods in the Model)

Can you please explain with a simple example??
Thanks
Padmaja
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937

Can you please explain with a simple example??

Certainly, here it is:

Notice how Model, View, and Controller are each responsible for a narrow, well defined set of responsibilities. Ultimately, this translates into a high level of reuse. For example, you can replace JTable in the GUI with some other widget, and not a single line of code needs to change in Model or Controller. Similarly, you can change the business logic in the model, and again, nothing needs to change in the Controller or the View.
Eugene.
Padmaja Prasad
Ranch Hand

Joined: Nov 14, 2001
Posts: 76
Notice how Model, View, and Controller are each responsible for a narrow, well defined set of responsibilities. Ultimately, this translates into a high level of reuse. For example, you can replace JTable in the GUI with some other widget, and not a single line of code needs to change in Model or Controller. Similarly, you can change the business logic in the model, and again, nothing needs to change in the Controller or the View.
Eugene.

Thank you so much Eugene. Now the MVC concepts are clear to me...
Thanks
Padmaja
Saraswathy Krishnamoorth
Ranch Hand

Joined: Mar 07, 2003
Posts: 73
Eugene:
Can u provide a detailed explaination. I could not understand the following code in the example:

// The callback method, -- Mark's idea
public void searchFlightsAction(ActionListener action) {
searchFlightsButton.addActionListener(action);
}

registerListeners method
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937

Can u provide a detailed explaination. I could not understand the following code in the example:
// The callback method, -- Mark's idea
public void searchFlightsAction(ActionListener action) {
searchFlightsButton.addActionListener(action);
}

Well, as I put in the comment line, this is Mark's idea that I happen to like. Mark call these the "hook" methods, and I call them the "callback" methods. The idea is to add the event listeners outside of the View. Since it is the Controller responsibility to listen to user actions, adding of the listeners logically belongs to Controller. So your Controller has code like

And as you can see, the controller uses the callback method in the View to add a listener to the "search flights" button. This is just a clever thing to do to avoid referencing specific GUI controls in the controller, when adding action listeners to them, that's all.
Eugene.
Saraswathy Krishnamoorth
Ranch Hand

Joined: Mar 07, 2003
Posts: 73
Thanks Eugene. Now it is clear.
Padmaja Prasad
Ranch Hand

Joined: Nov 14, 2001
Posts: 76
Hi Eugene,
Everything working fine, except that the JComboBox values are not populating when the Window is opened. I have added a WindowListener to the main window (View)and put the getFieldValues() method in the WindowOpened()of the controller class. But nothing is coming up while opening the window. Any idea what might be the reason??
In the mean time what type of listeners you used for populating combobox values(to appear at application start up).
Thanks
Padmaja
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937

Everything working fine, except that the JComboBox values are not populating when the Window is opened. I have added a WindowListener to the main window (View)and put the getFieldValues() method in the WindowOpened()of the controller class. But nothing is coming up while opening the window. Any idea what might be the reason??

I would suggest that you don't use WindowListener as the trigger for populating the origin/destination comboboxes. Rather, it should be either a) connect to database action (if you are implementing the dynamic on the fly switching of the database, or b) the call to a corresponding method in the model, when your model is instantiated.

Eugene.
[ March 13, 2003: Message edited by: Eugene Kononov ]
Padmaja Prasad
Ranch Hand

Joined: Nov 14, 2001
Posts: 76
Originally posted by Eugene Kononov:

I would suggest that you don't use WindowListener as the trigger for populating the origin/destination comboboxes. Rather, it should be either a) connect to database action (if you are implementing the dynamic on the fly switching of the database, or b) the call to a corresponding method in the model, when your model is instantiated.

Eugene.
[ March 13, 2003: Message edited by: Eugene Kononov ]

Thanks a lot Eugene. I will try this..
Padmaja
Padmaja Prasad
Ranch Hand

Joined: Nov 14, 2001
Posts: 76
Hi,
Which class is better for constructing the criteriaString:
"Origin='"+view.getOriginValue()+
"',Destination='" + view.getDestinationValue()+...
Controller or View??
Padmaja
Paul Moon
Greenhorn

Joined: Mar 12, 2003
Posts: 4
Hi all,
I am new to this group, and this is my first posting, (I have been reading through the threads here intensely for the last few days - trying to catch up and not repeat earlier questions).
Eugene, thanks for your code sample on this thread, it simplified things immensely. However I have a quick question,
Given your comment at the top of the code sample that this is in fact an Observer-Observable pattern, would it be advantagous to this philosophy to use the Observer interface and Observable class thus making the MainFrame a subclass of Observable, and the FlightsController implement the Observable interface.
Using this strategy, MainFrame could not subclass JFrame - it would become a private instance variable and would thus have to be manipulated by MainFrame thus further encapsulating the view and strenghthening the API between the model and the view. I realize your code sample was purely to highlight the MVC pattern, however I'm not sure if I'm getting too tied up in the generalities of applying patterns to the assignment, and would appreciate any comments/criticism's of using the Observer/Observable classes/interfaces provided by Sun to implement the MVC for the GUI.
Thanks in advance,
Paul
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937

Given your comment at the top of the code sample that this is in fact an Observer-Observable pattern, would it be advantagous to this philosophy to use the Observer interface and Observable class thus making the MainFrame a subclass of Observable, and the FlightsController implement the Observable interface.

I assume you are refering to Sun's java.util.Observable and java.util.Observer, and you probably meant to say that MainFrame should implement Observer, not to extend Observable. Yes, you could use these two classes, sure. The java.util.Observable has a serious limitation, though. Since it is a class, not an interface, your model is forced to be a stand-alone class that extends Observable. That is, your model cannot extend any other class. There is also certain "heavyness" and rigidness in the Observer-Observable. For these reasons, the Sun's built-in Observer-Observable is often replaced with custom implementations, and this is what I chose to do.
Eugene.
Rajesh Hegde
Ranch Hand

Joined: Sep 15, 2000
Posts: 112
Great discussion and a great example by Eugene.
The concept of MVC seemed ever-elusive for me to grasp....but with this discusson things are very clear to me. When i get to design UI the next time, i will try to capitalize on the knowledge i gained today.
-Rajesh
S. Ganapathy
Ranch Hand

Joined: Mar 26, 2003
Posts: 194
Hi All,
I am a new joinee to this group. I found the discussion in this thread is interesting.
Hi Eugene,
When registerListeners() method is called by the controller. I am bit confused.
componentInstance.addActionListener(handler);
when ever the componentInstance receives action event, "handler" object will handle the actions.
But in our case, who is the action event generator?
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937

But in our case, who is the action event generator?

The callback method in GUI adds a listener:

And the anonomous class in the controller is the listener that handles the event:

Eugene.
Paul Moon
Greenhorn

Joined: Mar 12, 2003
Posts: 4
Hi Eugene,
Thanks for your feedback.
Yes I was talking about sun's java.util.Observer and Java.util.Observable, and yes I did get my classes switched around.
I guess I'm eluding to the requirement for re-using known solutions as opposed to re-inventing the wheel. I have a lot of C++ experience, and like to think I understand OO concepts pretty well, but have very limited practical Java experience. Therefore I found your comments very useful with regards to the limitations of sun's implementation of Observer/Observable.
I guess I need to try it out and see how limiting it becomes, but you have certainly pointed me in the right direction when it comes to making my final choice.
Thanks again
Paul
S. Ganapathy
Ranch Hand

Joined: Mar 26, 2003
Posts: 194
Hi Eugene,
Thankyou verymuch
GVRao
Claudio Luz
Greenhorn

Joined: Feb 13, 2003
Posts: 27
Hi, friends.
I am implementing the user interface. I am using
the "tip" of Eugene and Mark for implement it.
My user interface has 3 files:
1. DataView
This class takes care of assembling of components such as the controls buttons for booking seats and looking flights. Also, display the ouput section in a table-like format to display the available flights.
It is implementing callback methods, too.
2. DataController
This class is designed to be the interface between the user and the DataView class.
It is containing some inner classes that
promptes a dialog box and the help on line,
too.


3. DataModel
DataModel is implementing all bussiness logic for the methods looking flights and booking seats.
When that methods are requested. DataModel also
notifies DataView. I am using the Observer-Observable pattern to get this goal.

My menu bar has the following options:
1. File --> Quit to quit the application
2. Help -> Promptes a help on line.
Can I implement the menu bar in the DataView class?
Other ask...
When the user click on book seat button is displayed a dialog box resquesting the number of
seats for booking... I am implementing this dialog box by using a inner class in the DataController class.
For example, my DataController has:
dataView.bookSeatsAction( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
// Get the most recently selected row index
String flightNumber =
datView.getFlightNumber();
String seatsToBook =
datview.getFlightSeats();
bookSeats(flightNumber, seatsToBook );
}
});
... and the bookSeat method is
public void bookSeats(
String flightNumber, int seatsToBook ) {
try {
// Promptes a dialog box for booking seats
BookSeatDlg bookSeatDlg =
new BookSeatDlg( dataView, dataModel );
}
catch ( FBNException fbe ) {
// do something
}
}
Note that BookSeatDlg indicates a dialog box
that is a inner class was implemented in the
DataController class.
I think that when a item on the menu bar
was chosen namely help on line will be the DataController class takes care of instantiate
a class called FBNHelp and after that display the help on line. Maybe, FBNHelp also will be impemented as a inner class in DataController class.

Comments, please.
Claudio Luz.
Claudio Luz
Greenhorn

Joined: Feb 13, 2003
Posts: 27
GALLUP GALLUP UP :roll:
Comments, please..
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17258
    
    6

Can I implement the menu bar in the DataView class?

Yes. Everything else looks fine from my glance at it.
Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Claudio Luz
Greenhorn

Joined: Feb 13, 2003
Posts: 27
Thanks very much, Mark.
Just more an question.
I implemented an inner class representing a dialog box in my controller as describe above.
For example, there are inner classes that is prompted when the user click on button bookSeats.
That dialog box uses DataModel which notify the DataView about confirmation of booking, and this way updates the output section for reflecting the newest number of available seats.
Is it such approach valid?
Comments, please.
Claudio Luz
Marcos Motta
Ranch Hand

Joined: Apr 28, 2002
Posts: 56
Hi Eugene,
Dont you think that the design you sugested is "too much" for the the SCJD assingment? The assignment states that "A clear design, such as will be readily understood by junior programmers, will be preferred to a complex one"
Do you I think that, for such a small application as de SCJD, the controller "role" should be coded in a separate class?
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937
Dont you think that the design you sugested is "too much" for the the SCJD assingment? The assignment states that "A clear design, such as will be readily understood by junior programmers, will be preferred to a complex one"
Do you I think that, for such a small application as de SCJD, the controller "role" should be coded in a separate class?

It doesn't matter how small the application is. What matters is the good software engineering principles, -- class cohesion, encapsulation, low coupling, clarity, ease of code change and maintainance. No, I don't think MVC is "too much" for SCJD assignment, -- I would even argue that it is a must, given the requirements for code reuse.
Eugene.
Marcos Motta
Ranch Hand

Joined: Apr 28, 2002
Posts: 56
Eugene,
I think I haven't made myself clear. I agree with you, 100% percent, that MVC is a must, regardless the size of the project.
My point is that we can implement MVC in different levels of complexity, each level adapted to the size of the problem we are trying to solve. I think that the implementation of MVC should not be more complex than the problem being solved.
The three roles: M,V and C; must be implemented separatedly (separation of roles is the key point in MVC), but not necessarily separated by a class. For the FBN, I think that the controller role could be played by listeners coded as inner classes in the main frame without breaking the MVC rules. These listeners would be "reacting to the user gestures", sending messages to the model and updating the view with the results. I defend the implemention of the model as a separated class. In FBN this class would have methods like BookFlight(), SearchFlights(), etc.
Marcos
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937

The three roles: M,V and C; must be implemented separatedly (separation of roles is the key point in MVC), but not necessarily separated by a class. For the FBN, I think that the controller role could be played by listeners coded as inner classes in the main frame without breaking the MVC rules. These listeners would be "reacting to the user gestures", sending messages to the model and updating the view with the results.

Yes, that's certainly an option. However, since your controller is defined as an inner class of the View, you may have some trouble adding an additional View to you MVC. I mean, what's the plan? What would act as a controller for that additional View, -- another set of inner class in that view? The existing set of inner classes in the original View? Just something to consider.
Eugene.
Marcos Motta
Ranch Hand

Joined: Apr 28, 2002
Posts: 56
Eugene,
In my opinion, there is no such thing as "the controller", but pieces of the code that plays the controller role.

What would act as a controller for that additional View, -- another set of inner class in that view?

That would not be a bad idea. I dont see any reason for the controller to carry the burden of having to deal with all views in the system. In the java blueprints description of MVC -- see http://java.sun.com/blueprints/patterns/MVC-detailed.html -- one of the caracteristics pointed out for the controller is "one for each functionality". How would you interpret this?
Web application is another history. In this kind o app, a unique controller (front controller) taking care of routing all view requests to the model and redirecting the results to the corresponding views really makes things easier , and it is worth it even for small apps.
Marcos
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confused with MVC