Model View Controller - PowerPoint PPT Presentation

1 / 52
About This Presentation
Title:

Model View Controller

Description:

... Xiaoping Jia, Addison Wesley, Second Edition, 2003, ISBN 0-201-73733 ... Do not imbed the user interface code inside the model. Keep the two separate. 12-18 ... – PowerPoint PPT presentation

Number of Views:153
Avg rating:3.0/5.0
Slides: 53
Provided by: andr114
Category:

less

Transcript and Presenter's Notes

Title: Model View Controller


1
Model View Controller
  • C Sc 335
  • Object-Oriented Programming and Design
  • University of Arizona Fall 2006

2
Acknowledgements
  • These slides were written by Andrew Oplinger,
    Richard Snodgrass, Amanda Wixted and Ken Sung,
    using aspects of Sun Javas API and
    Object-Oriented Software Development Using Java,
    by Xiaoping Jia, Addison Wesley, Second Edition,
    2003, ISBN 0-201-73733-7.

3
Outline
  • Model versus Application
  • MVC
  • TicTacToe Example
  • Summary

4
Outline
  • Model versus Application
  • Regular Control Flow (Polling)
  • Rudimentary Inverted Application Control Flow
  • Modified Polling Application Control Flow
  • Model
  • Safety
  • MVC
  • TicTacToe Example
  • Summary

5
Model versus Application
  • Control flow the path in which a program
    executes a section of code.
  • Application short for application program, which
    is a program designed to perform a specific
    function.
  • Model include a collection of software components
    that programmers use to build applications for
    the domain the model addresses.
  • Model can contain specialized APIs, services, and
    tools, which reduce the knowledge a user or
    programmer needs to accomplish a specific task.

6
Regular Application Control Flow
  • User starts program in main method
  • While (true)
  • display the state
  • query the user for input
  • execute the input
  • print the results
  • Examples
  • see NormalControlFlow.java
  • see NormalControlFlowWMethods.java

7
UML Diagram of Polling (using methods)
NormalControlFlowWModel
-checkTie(int)boolean -displayState(int)
-hasWon(int)int -isValid(int,int,int)boo
lean -switchPlayer(int)int main(String)
8
Regular Application Control Flow Summary
  • This control flow is called polling ReadLine.
  • (Think of it as a petulant child asking, are
    we there yet?)
  • The system is a complete procedural set of
    instructions.
  • Advantages
  • quick and straightforward.
  • works very well for small systems with one input.
  • Disadvantages
  • The system is hung waiting for input that may
    never come.
  • The system must be created whole cloth every time.

9
Rudimentary Inverted Application Control Flow
  • Application programmer creates a reactionary
    library that performs the computation.
  • User starts program in main method.
  • Program creates Model object.
  • while(true)
  • query the user for input
  • send input to Model for calculation
  • print results from the Model
  • Example
  • see NormalControlFlowWModel.java

10
Extracting the Model
NormalControlFlowWModel
SafeModel ltltinterfacegtgt
static main(String )
getAt(int,int)int
- static displayState(TTTModel)
getSize( )int
hasWon( )boolean
isTie( )boolean
isValidMove( )boolean
TTTModel
- _safe SafeModel
- _board int
abstract Strategy
- _size int
- _current_player int
frame SafeModel
player_tag int
getSafe( )SafeTTTModel
getMove(i)Move
makeMove(Move)
Move
- final col int
BaseStrategy
- final row int
getMove( )Move
- final player int
- getCol( ) int

11
A Wrench In The Works
  • What if you are creating a system that needs
    input from more then one device?

12
Modified Polling Application Control Flow
  • Application programmer creates a reactionary
    library that performs the computation.
  • User starts program in main method
  • Program creates Model object
  • while (true)
  • while (there is no input)
  • query the user for input from device 1 for a few
    milliseconds
  • query the user for input from device 2 for a few
    milliseconds
  • send input to Model for calculation
  • print results from the Model
  • What if we want input from every key in the
    keyboard, and a mouse, and a network? Does this
    work?

13
Models
  • In the previous examples, the model section of
    code worked independent of input, reacting
    correctly and updating the system.
  • We can use the same approach to handle multiple
    inputs.

14
Safety
  • Previously, code was created without the
    possibility of someone malicious using it and
    breaking.
  • Now, you must create a model with access
    restrictions.
  • Example see Strategy.java

15
Ensuring Safety
  • Do not use public fields.
  • Use interfaces to regulate what access other
    objects have to your model.
  • If further access restrictions are required,
    create a private inner class that implements the
    above interface, pass an instance of the inner
    class ensuring the calling object cannot use
    casting to get around interface restrictions.
    This is called a type-safe class.
  • Example see TTTModel.java, and SafeModel.java

16
Outline
  • Model verses Application
  • MVC
  • Model-View Separation
  • Fully Inverted Application Control Flow
  • Model-View-Controller Separation
  • Tying All Together
  • Multiple Views in Java
  • TicTacToe Example
  • Summary

17
Model-View-Controller (MVC)
  • MVC is a refinement of the Observer pattern.
  • Decoupled user interfaces
  • One model may have several user interfaces.
  • Web, phone, PDA, GUI on a desktop
  • Each user interface (UI) will hook into the same
    model.
  • But allow IO in different ways
  • Desired change UI without changing the model.
  • Desired change the model without changing the
    UI.
  • Do not imbed the user interface code inside the
    model. Keep the two separate.

18
Model-View Separation
  • Model-view separation separate core data of our
    program away from the GUI
  • Model classes that maintain data or state of our
    program do not contain information about how
    that state is shown to the user.
  • View classes that present the data in the model
    to the user, and/or allow her to interact with it
    (often this is the programs GUI).

19
Benefits of Model/View Separation
  • Keeps complex game behavior out of GUI, so GUI
    classes can focus on graphical issues.
  • Keeps model modular, so it could be used with a
    different GUI or another view altogether, such as
    a text view.
  • Enables you to have hot-swappable views.

20
Fully Inverted Application Control Flow
  • Application programmer creates a library that
    addresses each action that the user can take.
  • She sets up sections of code for each type of
    input that will call the appropriate action.
  • A general model fulfills these functions
  • check to make sure proposed change is a valid
    one.
  • make the change and perform the computations.
  • have access to retrieve the current state of the
    model.
  • Example see TTTModel.java

21
Model-View-Controller
  • MVC is an adaptation of an older, more detailed
    model/view paradigm.
  • Controller classes for coordination of
    interaction with the user. Typically this
    includes event handlers for input and also the
    GUI components that gather that input.

22
Outline
  • Model verses Application
  • MVC
  • Model-View Separation
  • Fully Inverted Application Control Flow
  • Model-View-Controller Separation
  • Tying All Together
  • Multiple Views in Java
  • TicTacToe
  • Summary

23
Tying It All Together MVC
  • Model
  • The section of code responsible to handle the
    state of the application and make decisions
    according to the specfication
  • View
  • The section of code responsible for presenting
    the data to the user.
  • Controller
  • The section of code responsible for receiving
    input from the user.
  • Example TTTModel.java, ButtonView.java,
    TTTView.java, PaintView.java

24
MVC Bubble Diagram
MVC Bubble Diagram
View
2. Since the control has no knowledge of the
graphical representation, it need to consult the
View to interpret the input. (Note that not all
input are necessary to be interpreted by the
View).
6. The View may need to request information from
the Model to update accordingly
  • Give the graphical representation to the user
  • Update the graphics accordingly

5. The Model notifies the View to update the
graphic as many times as necessary.
Control
Model
  • -Handles users inputs
  • Consult the view to interpret an input if
    necessary
  • Inform the model of the user input
  • Make some decisions on the control flow

-Core of the system -The only place to have the
state of the system -Make decisions for the
system -Update the system status
1. The user input is sent to the Control. The
next logical step is to inform the Model about
it. But since the input might be data irrelevant
to the system (e.g.. the coordinates of a pixel),
it would need to translate it to system-relevant
information.
4. The Model response to the user input
accordingly. It may change the state of the
system, saves the user input, fire certain
events, etc
3. After the input is translated into
system-relevant information, it can inform the
Model about it. In some cases the Control may
choose to ignore the input. e.g.. It is so
irrelevant to the system.
25
Outline
  • Model verses Application
  • MVC
  • Model-View Separation
  • Fully Inverted Application Control Flow
  • Model-View-Controller Separation
  • Tying All Together
  • Multiple Views in Java
  • TicTacToe Example
  • Summary

26
Multiple Views in Java
  • Use the Observer/Observable classes.
  • Write an abstract View superclass panel.
  • Make View an Observer.
  • Extend View for all actual views (give each its
    own unique paintComponent method to draw the
    models state in its own way).
  • Provide a mechanism in the GUI to set the view
    (perhaps through menus).
  • To set view, attach it to observe the model.
  • Write the Model as a subclass of Observable.

27
Issue Layout Validation
  • When view is changed, old view panel should be
    removed from screen and the new view put on the
    screen.
  • This requires you to remove and add panels to an
    on-screen container (likely the frames content
    pane).
  • By default, changes to a container that is
    already showing on screen do not show up unless
    the layout is validated.
  • Validation is the equivalent of repainting, for
    layout
  • Validate a container by calling public
    void validate() on it.

28
Example Changing Views
  • // in the frames event listener
  • if (event.getSource() textViewButton)
  • // remove old view add new one
  • Container cp getContentPane()
  • cp.remove(myView)
  • myModel.deleteObserver(myView)
  • myView new TextView()
  • myModel.addObserver(myView)
  • cp.add(myView, BorderLayout.CENTER)
  • cp.validate()

29
Outline
  • Model verses Application
  • MVC
  • TicTacToe Example
  • Introduction
  • TicTacToe UML Diagram
  • Initialization Sequence Diagram
  • Full Sequence Digram
  • PaintView Sequence
  • In Terms of MVC
  • Common Mistakes
  • Questions
  • Summary

30
TicTacToe UML Diagram
TTT
TTTFrame
static main()
  • - views
  • model TTTModel

1
Observable
ltltinterfacegtgtSafeModel
1
Observer
TTTModel
isValid(Move) boolean isTie() boolean
hasWon() int getSize() int getAt(int, int)
int

MakeMove(Move) newGame()
ltltabstractgtgtTTTView
1
1
safe SafeModel
registerListener() translate(ActionEvent)
Move invalidMove() reset()
1
TTTModelSafeImplementation

ltltabstractgtgtStrategy
ButtonView
PaintView
- safe SafeModel
Move
getMove()
TTTFrameButtonListener
  • row int
  • col int
  • player int


- view TTTView
BaseStrategy
actionPerformed(ActionEvent)
getRow() int getCol() int getPlayer int
getMove()
TTTFrameButtonListener

- view TTTView
mouseClicked(MouseEvent)
31
Initialization Sequence Diagram
32
Full Sequence Diagram of TTT
SafeImplementation
MouseClickListener
PaintView
mouseClicked( MouseEvent)
TTTView
TTTModel
BaseStrategy
isEnabled()
translate(MouseEvent)
new()
Move
return Move
isValid(Move)
makeMove(Move)
setChanged()
notifyObservers()/update()
isTie()
hasWon()
getAt()
isTie()
hasWon()
getMove()
new()
compMove Move
setChanged()
notifyObservers()/update()
hasWon(), isTie(), getAt()
x
x
33
PaintView Sequence Diagram
PaintView
g2 Graphics2D
TTTModel
update()
repaint()
paintComponent(g2)
drawVirtLines()
drawHorzLines()
getAt()
Line2D
new()
draw(Line2D)
X
Ellipse2D
new()
draw(Ellipse2D)
X
34
Outline
  • Model verses Application
  • MVC
  • TicTacToe Example
  • Introduction
  • In Terms of MVC
  • TicTacToe UML Diagram
  • Package Diagram
  • TTT Bubble Diagram
  • Simplified Sequence Diagram in MVC
  • Common Mistakes
  • Questions
  • Summary

35
TicTacToe UML Diagram (divided into MVC modules)
TTT
TTTFrame
static main()
  • - views
  • model TTTModel

1
Observable
ltltinterfacegtgtSafeModel
1
Observer
TTTModel
isValid(Move) boolean isTie() boolean
hasWon() int getSize() int getAt(int, int)
int

MakeMove(Move) newGame()
ltltabstractgtgtTTTView
1
1
safe SafeModel
View
registerListener() translate(ActionEvent)
Move invalidMove() reset()
1
TTTModelSafeImplementation

ltltabstractgtgtStrategy
ButtonView
PaintView
- safe SafeModel
Move
getMove()
TTTFrameButtonListener
  • row int
  • col int
  • player int


- view TTTView
BaseStrategy
actionPerformed(ActionEvent)
getRow() int getCol() int getPlayer int
Control
getMove()
TTTFrameButtonListener

- view TTTView
Model
mouseClicked(MouseEvent)
36
Package Diagram
37
6. The View asks the Model if the game has ended
via isTie() and hasWon(), or it uses getAt() to
get the current game board. Then it update the
graphics accordingly.
MVC Bubble Diagram for TTT
View
2. PaintView uses its width and height
information to determine the move user made.
  • Draw the game board and moves
  • Draw appropriately when the game has ended.

5. Every time the game board is updated, the
Model notifies the View to update.
Control
Model
  • -Receives all mouse clicks, button or key
    pressed.
  • Consult the view to interpret an input when a
    mouse click has happened or a button is pushed.
  • -Store the game board as a 2D int array.
  • Decide if the game has ended, or a computer move
    is needed.
  • Compute the next computer move.

1. A mouse click is sent to the Control. The
mouseClicked() is invoked. The click is simply
the coordinates of a pixel. The Control calls
translate() of the PaintView to interpret the
input.
4. The Model updates the game board with the user
move. If the game is not ended, it will ask the
BaseStrategy for the computer move and update the
board.
3. After the Control receives the result from
translate(), it checks a) if it can be
interpreted as a move, if not it will ignore the
input (but only happen in PhoneView), and b) if
it is a valid move, if not it notifies the views
to update. If it is a valid move, it informs the
model via makeMove().
38
Simplified TTT Sequence Diagram Relative to MVC
MouseClickListener
SafeImplementation
PaintView
TTTView
TTTModel
BaseStrategy
1
mouseClicked( MouseEvent)
  • The user clicked on the board, a MouseEvent is
    fired and mouseClicked() is invoked in the
    listener.

39
Simplified TTT Sequence Diagram Relative to MVC
MouseClickListener
SafeImplementation
PaintView
TTTView
TTTModel
BaseStrategy
1
mouseClicked( MouseEvent)
2
translate(MouseEvent)
  • The input from user is passed to the view and get
    translated to information that is relevant to the
    game (a Move).

40
Simplified TTT Sequence Diagram Relative to MVC
MouseClickListener
SafeImplementation
PaintView
TTTView
TTTModel
BaseStrategy
1
mouseClicked( MouseEvent)
2
translate(MouseEvent)
3
makeMove(Move)
  • The listener informs the model about the move.

41
Simplified TTT Sequence Diagram Relative to MVC
MouseClickListener
SafeImplementation
PaintView
TTTView
TTTModel
BaseStrategy
1
mouseClicked( MouseEvent)
2
translate(MouseEvent)
3
makeMove(Move)
4
notifyObservers()/ update()
  • The game board is changed, the model notifies the
    views to update the graphical representation to
    the user.

42
Simplified TTT Sequence Diagram Relative to MVC
MouseClickListener
SafeImplementation
PaintView
TTTView
TTTModel
BaseStrategy
1
mouseClicked( MouseEvent)
2
translate(MouseEvent)
3
makeMove(Move)
4
notifyObservers()/ update()
5
hasWon(), isTie(), getAt()
  • The views check the status of the game (via
    hasWon(), isTie()), and get the appropriate
    information (via getAt()) from the model to
    update themselves.

43
Simplified TTT Sequence Diagram Relative to MVC
MouseClickListener
SafeImplementation
PaintView
TTTView
TTTModel
BaseStrategy
1
mouseClicked( MouseEvent)
2
translate(MouseEvent)
3
makeMove(Move)
4
notifyObservers()/ update()
5
hasWon(), isTie(), getAt()
6
getMove()
  • The model asks the current Strategy for the next
    computers move.

44
Simplified TTT Sequence Diagram Relative to MVC
MouseClickListener
SafeImplementation
PaintView
TTTView
TTTModel
BaseStrategy
1
mouseClicked( MouseEvent)
2
translate(MouseEvent)
3
makeMove(Move)
4
notifyObservers()/ update()
5
hasWon(), isTie(), getAt()
6
getMove()
  • The game board is changed again, the model
    notifies the views to update.

7
notifyObservers()/ update()
hasWon(), isTie(), getAt()
45
Simplified TTT Sequence Diagram Relative to MVC
MouseClickListener
SafeImplementation
PaintView
TTTView
TTTModel
BaseStrategy
1
mouseClicked( MouseEvent)
2
translate(MouseEvent)
3
makeMove(Move)
4
notifyObservers()/ update()
5
hasWon(), isTie(), getAt()
6
getMove()
7
  • The system returns to wait for the next users
    input.

notifyObservers()/ update()
hasWon(), isTie(), getAt()
8
46
Outline
  • Model verses Application
  • MVC
  • TicTacToe Example
  • Introduction
  • In Terms of MVC
  • Common Mistakes
  • Questions
  • Summary

47
Common Mistakes
  • Some state of the system is stored in View or
    Control
  • Control is making decisions for the Model where
    these decisions are best to reside in Model
  • Control store some states or information about
    the graphical representation that is/should hold
    by the View.
  • In short, a module does not handle the task that
    it should, and/or handles the task that another
    module should.

48
Outline
  • Model verses Application
  • MVC
  • TicTacToe Example
  • Introduction
  • In Terms of MVC
  • Common Mistakes
  • Questions
  • Summary

49
Questions
  • 1. If the game is changed from a 3x3 TicTacToe to
    a 4x4 TicTacToe, what change(s) is necessary in
    the system? What changes does the PaintView need
    to show a 4x4 game board?

A The only change necessary is to use 4 as the
parameter when creating the TTTModel object in
TTT.java. The PaintView will draw a 4x4 game
board accordingly using getSize().
50
Questions
  • 2. What inputs that the Control get but does not
    inform the Model?
  • A Inputs that can not be interpreted as a move,
    Invalid moves, exiting the game, switching views.

51
Questions
  • 3. After the TTTFrame realizes the user has made
    an invalid move, it calls invalidMove() in the
    View(eg. PaintView), and the TTTModel does not
    know of this invalid move. What arguments one
    might use to claim that this does not perfectly
    comply with the MVC principles? What changes can
    the author made to overcome these problems?

A The Control assumes the Model would not want
to know about an invalid move. This assumption
is not necessary true (specially when
requirements changes in the future). The author
can have the Control pass the invalid move to the
Model, and let the Model to decide what to do
next, eg. calling invalidMove()
52
Summary
  • The computations can be extracted into a model
    module, separating from the code handling input
    and output.
  • MVC
  • Views interact with the Model to display the
    state.
  • Controllers interact with the Model to create
    change.
  • The Model encapsulates the state of the
    application.
Write a Comment
User Comments (0)
About PowerShow.com