Upload
lana-burnett
View
16
Download
1
Embed Size (px)
DESCRIPTION
Java. Model-View-Controller - see http://doc.qt.nokia.com/latest/model-view-programming.html#concepts. Design Patterns. The hard problem in O-O programming is deciding what objects to have, and what their responsibilities are - PowerPoint PPT Presentation
Citation preview
1
Java
Model-View-Controller - seehttp://doc.qt.nokia.com/latest/model-view-programming.html#concepts
2
Design Patterns
The hard problem in O-O programming is deciding what objects to have, and what their responsibilities are
Design Patterns describe the higher-level organization of solutions to common problems
They are a current hot topic in O-O design
3
The MVC pattern
MVC stands for Model-View-Controller
The Model includes the data and how it is managed.
E.g. the Client and ArrayList classes in Dating Service project
The City and Hashmap classes in HPAir
View & Controller
The View (or a View) is a way of looking at or displaying the model -
E.g the Gui components and textfields in HPAIR
The Controller handles user input and modifications to the view
E.g. The ControlPanel with the listener in ControlPanel in the HPAIR project
4
6
Thus, the MVC pattern hinges on a clean separation of objects into one of three categories :
1. models for maintaining data – INCLUDE A MANAGER FOR THE DATA
(E.G. an ArrayList OR Hashmap) to store operations on it
Advantage of Using MVC
MVC
2. views - for displaying all or a portion of the data e.g. TextPanel class in HPAir
3. controllers for handling events that affect the model or view(s). E.g. (ControlPanel in Hpair)
7
Advantage of Using MVC
Because of this separation of roles,
multiple views and controllers can interface with the same model.
Even new types of views and controllers that never existed before
can interface with a model without forcing a change in the model design.
8
9
The MVC abstraction can be graphically represented as follows.
Event is passed to the controller
Controller notifies the View(s) or the Model of changes
View gets data from the model
Model updates Views when data changes
10
The Model - Summary The Model is used to
1) manage information and 2) notify observers when that information changes.
It stores :
1) application’s data 2) and defines the logic that manipulates that data.
E.g. In the database of people in a Dating Service , A) clients represent the data and B) the ArrayList class manages the data. Combined they represent the Model.
MODEL
The Model contains a method -
notifyObservers -
that will notify classes when changes that occur to it.
11
Model details
A view has a constructor
It takes a reference to a model and registers for updates from it.
There are different opinions on how to manage them
but their separation is undisputed.
12
Model
If you need to model two groups of If you need to model two groups of unrelated data and functionality,unrelated data and functionality,
you create you create two separate models.two separate models.
13
Model as an abstraction
A model is meant to serve as an abstraction A model is meant to serve as an abstraction of some real world process or system of some real world process or system
e.g. a e.g. a queue of people in a security line, queue of people in a security line,
This makes it very easy to use real-world This makes it very easy to use real-world modeling techniques in defining your modeling techniques in defining your models. models.
14
15
MODEL
Examples of data for a model – real world objects: Book Person Passenger Invoice City Client
16
0
0.05
0.1
0.15
0.2
0.25
0.3
0.35
0.4
0.45
A B C D
A = 50%
B = 30%
C = 20%
The above model contains some data.
The views for it could be a spreadsheet display,
a bar graph or a pie chart.
A
B
C
D
We use the same model to produce two views.
17
MVC
Ideally, a model has no connection to the user interface used to present and edit it.
For example, if you have a model that represents a person (say you are writing an address book),
you might want to store a birth date.
Model and interaction with classes
However, storing a date format string or
how that date is to be presented should be done elsewhere.
18
19
Controller - What it does
A GUI lets the user control what work the program is doing
The Controller is the means by which the user interacts with the application.
HOW??? Did you do this in your current project?HOW??? Did you do this in your current project?
CONTROLLER
HOW?
A Controller accepts input from the user and instructs the model and view
to perform actions based on that input.
E.g. the listener class in your DatingService project -
Records that you need to “find by hobby”
20
Controller
E.g. a button is pushed and
the controller informs the view to change the its appearance
E.g. if the user clicks the mouse button
or chooses a menu item,
21
Controller
the Controller is responsible for determining how the application should respond.
Typically controllers have logic that is specific to an application.-
e.g. what to do when a user pushes a button22
23
Controller
Controllers make sure the views have access to the model classes they need to display.
E.g. controller classes have a reference to both the view and the model.
Controllers are often the least reusable objects in an application, but that’s acceptable.
You can’t reuse everything!!!!
24
The View
The user has to be able to see, or view, what the program is doing
The View displays what the Controller notifies it to display
The Model is independent of the View but it can provide access methods ( getters) so the view can get information from it.
25
The View
The view should not be responsible for storing the data it is displaying,
---- the model contains the data.
In addition, when the model changes,
the view is told to redraw the image to reflect those changes.
26
Views
The controller layer notifies the view of changes to the model
View objects tend to be reusable,
and provide consistency between applications.
Code Re-USE
We can re- use a panel that draws images
Or the DatingService organization of components
e.g. display results of a search in a JTextArea
A panel of combo boxes
28
29
Combining the Controller and View
Sometimes the Controller and View are combined, especially in Sometimes the Controller and View are combined, especially in small programssmall programs
Combining the Controller and View is appropriate if they are Combining the Controller and View is appropriate if they are very very interdependentinterdependent
The The Model should still be independent Model should still be independent of everythingof everything
NeverNever mix Model code with GUI code! mix Model code with GUI code!
30
MVC vs SWING
MVC separates the View and the Controller.
Swing does not separate the View and the Controller
At the component level, the components display data and handle events.
This is why your buttons are in the same class as the listener.
32
Separation of concerns
As always, you want code independence
The Model should not be contaminated with control code or display code
The Controller should talk to the Model and View by calling methods in the their classes.
34
The Bouncing Ball Applet
Each click of the Step button advances the ball a small amount
The step number and ball position are displayed in the status line
35
The Ball Applet: Model
The Ball Applet shows a ball bouncing in a window
The Model controls the motion of the ball by keeping track of its location .
To know when to bounce, the Model must know the size of the window
The Model doesn’t need to know anything else about the GUI
36
Model I
// contains only information about the ball’s location// Note that it has no reference to the view or controllerclass Model { final int BALL_SIZE = 20; int xPosition = 0; int yPosition = 0; int xLimit, yLimit; int xDelta = 6; int yDelta = 4; // more...
37
Model II
// contains a method to change the location void upDateLocation ( ) { xPosition += xDelta; if (xPosition < 0) { xPosition = 0; xDelta = -xDelta; } // more...
38
Model III
if (xPosition >= xLimit) { xPosition = xLimit; xDelta = -xDelta; } // still more...
// All it knows is the ball’s location and //keeps track of changes to the location
39
Model IV
yPosition += yDelta; if (yPosition < 0 || yPosition >= yLimit) { yDelta = -yDelta; yPosition += yDelta; } } // end of makeOneStep method} // end of Model class
// All it knows is the ball’s location and //keeps track of changes to the location
40
The Ball Applet: View
The View needs access to the ball’s state - in this case, its x-y location WHICH IS STORED IN THE MODEL.
Therefore it will receive a reference to the model in its constructor
It also needs a reference to the Controller to set the status display on the GUI.
The View doesn’t need to know anything else
41
View I
class View extends JPanel{ Controller controller; Model model; int stepNumber = 0;
// send references of the model and controller // send references of the model and controller to //the constructorto //the constructorpublic View(Controller controller, Model View(Controller controller, Model model) model) { this. Controller = controller this. Model = model// controller object often not needed}
42
View II
// draw the ball WHEN A BUTTON IS PRESSED// draw the ball WHEN A BUTTON IS PRESSEDpublic void paint (Graphics g) { g.setColor (Color.red);
g.fillOval (model.xPosition, model.yPosition, model.BALL_SIZE, model.BALL_SIZE); controller.showStatus ("Step " + (stepNumber++) + ", x = " + model.xPosition + ", y = " + model.yPosition); } // end paint method
43
The Ball Applet: Controller
The Controller interacts with the Model
The Controller tells the View when it needs to repaint the Controller tells the View when it needs to repaint the displaydisplay
The Controller doesn’t need to know the inner workings of the Model
The Controller doesn’t need to know the inner workings of the View
44
Controller I
public class Controller extends JApplet { Panel buttonPanel; Button stepButton; private Model model ; // set up view and // set up view and model model
private View view;
// more...
// IN AN APPLET THE INIT AND START METHODS ARE //CALLED AUTOMATICALLY ON STARTUP.
45
Controller IIpublic void init () // similar to a constructor in an application{ buttonPanel = new Panel ();// create the panel and butto();// create the panel and buttonn stepButton = new Button ("Step"); model = new Model (); // model needs no parameters
// send a reference to the model and a reference // send a reference to the model and a reference //to “this” class to the view//to “this” class to the view view = new View (this, model); // Lay out components setLayout (new BorderLayout ()); buttonPanel.add (stepButton); this.add (BorderLayout.SOUTH, buttonPanel); this.add (BorderLayout.CENTER, view);
46
Controller III // Attach actionlistener to the button stepButton.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent event) }// tell the model to update the location
model.updateLocation();model.updateLocation();
// tell the view to redraw the screen IN ITS // tell the view to redraw the screen IN ITS // PAINT METHOD// PAINT METHOD view.repaintview.repaint }});
// more...
47
Controller V
// set limit and start the drawing public void start ( ) // called automatically{ // gets size from the view AND STORES model.xLimit = view.getSize ( ).width - model.BALL_SIZE;
model.yLimit = view.getSize ( ).height - model.BALL_SIZE;
repaint (); // REDRAWS THE BALL } // end of start method
} // end of Controller class
Interactions
The viewview registers as a listener on the model. registers as a listener on the model.
The view receives receives notificationnotifications s when the model’s data is altered.
The model is not aware of the view or the controller -- it simply broadcasts changes to it to all interested listeners.
48
Interactions
The controller is bound to the view - NEEDS TO REPAINT WHEN BUTTON IS PRESSED
UserUser pressing a button invokes a registered listener method(actionPerformed() in the controller class.
The controller is given a reference to The controller is given a reference to 1) 1) the model in its constructor the model in its constructor 2 ) as well a reference to the view2 ) as well a reference to the view
49
Interactions
the model does not have a reference to the view.
The model uses event-notification methods to notify event-notification methods to notify the controller or the view. the controller or the view.
When a change in the data model occurs, change in the data model occurs,
each view is notified by a property change eventproperty change event
and can update itself accordingly.
50
51
Communication between Classes
The model can exist in isolation from its environment, unaware of the view and controller.
E.g., the clients in a JList do not know where they are presented.
A Bidder or Client class does not know how they will be used in the application.
52
Communication between Classes
Each view is associated with a unique controller.
A view has instance variables that are references to the Model(to get information) and Controller( to notify of events).
It receives the references in its constructor receives the references in its constructor -
but it may just have methods that the Controller can call.
SUMMARY
Input --> Processing --> OutputModel --> Controller --> View
The general principles of MVC are very simple: "Model is state;
View reacts to input and changes to model;
Controller reacts to view and changes to model;
Controller changes model and view".
53
MVC - Roles
54
Model1. Encapsulates Application State2. Responds to queries 3.Contains functionality for the state 4. Notifies view or controller of changes
State Query
View1. Displays the model2. Requests updates from model 3.Notifies Controller of user inputs 4. Allows Controller to select view
Controller1. Defines the application behavior2. Maps user inputs to model updates 3. Selects view for response
MVC
The model, view and controller are concepts –
“Generally you use a framework (like Struts)to define model, view and controller and their interactions.
See next slide
55
The Struts Framework is a standard for developing well-architected Web applications. It has the following features:
Open source
Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels: Model: application state View: presentation of data (JSP, HTML) Controller: routing of the application flow
Implements the JSP Model 2 Architecture
Stores application routing information and request mapping in a single core file, struts-config.xml
The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the developer. 56