1 / 49

Model View Controller (MVC) an architecture

Model View Controller (MVC) an architecture. Slides by Rick Mercer, Christian Ratliff, Oscar Nierstrasz and others. Outline. Java GUI Model Review of Observer Pattern Model-View-Controller Tic Tac Toe Example Spaghetti version MVC version. Readings. The Swing Tutorial

cjohn
Download Presentation

Model View Controller (MVC) an architecture

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Model View Controller (MVC)an architecture Slides by Rick Mercer, Christian Ratliff, Oscar Nierstrasz and others

  2. Outline • Java GUI Model • Review of Observer Pattern • Model-View-Controller • Tic Tac Toe Example • Spaghetti version • MVC version

  3. Readings • The Swing Tutorial http://docs.oracle.com/javase/tutorial/uiswing/index.html • Model View Controller • http://www.laputan.org/pub/papers/POSA-MVC.pdf

  4. AWT Components and Containers The java.awt package defines GUI components, containers and their layout managers. NB: There are also many graphics classes to define colours, fonts, images etc.

  5. Swing JComponents The javax.swing package defines GUI components that can adapt their “look and feel” to the current platform. P2 — GUI Construction

  6. Swing Containers and Containment Swing Containers may contain other Components Jbutton b = new Jbutton(“Push me”); Jpanel p = new Jpanel(); p.add(b);

  7. Layout Management The Layout Manager defines how the components are arranged in a container (size and position). JPanel p = new JPanel(new BorderLayout()); awt LayoutManagers swing LayoutManagers Container contentPane = frame.getContentPane(); contentPane.setLayout(new FlowLayout());

  8. An example: GridLayout A GridLayout places components in a grid of cells. • Each component takes up all the space in a cell. • Each cell is the same size GridLayout experimentLayout = new GridLayout(0,2); : compsToExperiment.setLayout(experimentLayout); compsToExperiment.add(new Jbutton(“Button 1”); compsToExperiment.add(new Jbutton(“Button 2”); P2 — GUI Construction

  9. The GameGUI The GameGUI is a JFrame using a GridLayout (with a 2 cells), and containing a Jpanel with a JLabel (Top), a JPanel (Down) with 9 buttons TTT:JFrame :JPanel :JPanel :JLabel :JButton The bottom Panel itself contains a grid of squares (JButtons) and uses a GridLayout. . . . . :JButton

  10. Laying out the GameGUI public class TicTacToe1 extends Jframe { … public TicTacToe1() { setTitle("Tic Tac Toe Version 1"); setSize(310, 210); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout (new GridLayout(2,1)); messageLabel = new JLabel("It is X turn."); msgPanel = new JPanel(new FlowLayout()); msgPanel.add(messageLabel); gamePanel = new JPanel(new GridLayout(3,3)); ………… add(msgPanel); add(gamePanel); setVisible(true); } P2 — GUI Construction TicTacToe v7-swing

  11. Helper methods Use a helper method to the hide details of GUI construction private void buildPanels() { messageLabel = new JLabel("It is X turn."); msgPanel = new JPanel(new FlowLayout()); gamePanel = new JPanel(new GridLayout(3,3)); msgPanel.add(messageLabel); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { gameButtons [i][j] = new JButton (""); gamePanel.add(gameButtons [i][j]); (gameButtons[i][j]).addActionListener (new GameSquareListener()); } } P2 — GUI Construction

  12. Interactivity with Events • To make your GUI do something you need to handle events • An event is typically a user action — a mouse click, key stroke, etc. • The Java Event model is used by Java AWT and Swing (java.awt.AWTEvent and javax.swing.event)

  13. Concurrency and Swing • The program is always responsive to user interaction, no matter what it is doing. • The runtime of the Swing framework creates threads — you don’t explicitly create them. • The Event Dispatch thread is responsible for event handling.

  14. Events and Listeners (I) Instead of actively checking for GUI events, you can define callback methods that will be invoked when your GUI objects receive events: Hardware events ... (MouseEvent, KeyEvent, ...) ... are handled by subscribed Eventistener objects AWT Framework/ Swing Framework Callback methods AWT/Swing Components publish events and (possibly multiple) EventListeners subscribe interest in them.

  15. Events and Listeners (II) Every AWT and Swing component publishes a variety of different events (see Java 7 documentation).

  16. Listening for Button events When we create the “New game” JButton, we attach an ActionListener with the JButton.addActionListener() method: You can instantiate an anonymousinnerclass to avoid defining a named subclass of ActionListener. private Component makeControls() { JButton again = new JButton("New game"); again.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showFeedBack("starting new game ..."); newGame(); // NB: has access to methods } // of enclosing class! }); return again; }

  17. Outline • Java GUI Model • Review of Observer Pattern • Model-View-Controller • Tic Tac Toe Example • Spaghetti version • MVC version

  18. The Observer Pattern • Also known as the publish/subscribedesign pattern - to observe the state of an object in a program. • One or more objects (called observers) are registered to observe an event which may be raised in an observable object (the observable object or subject). • The observable object or subject which may raise an event maintains a collection of observers.

  19. 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 • Design patterns are a major topic in O-O design

  20. b a c a b c x 60 30 10 y 50 30 20 z 80 10 10 Observer Pattern - Example Observers a b c a = 50% b = 30% c = 20% Subject requests, modifications change notification Observer Pattern, OOA&D, Rubal Gupta, CSPP, Winter ‘09

  21. Observer Pattern - Key Players • Subject • has a list of observers • Interfaces for attaching/detaching an observer • Observer • An updating interface for objects that gets notified of changes in a subject • ConcreteSubject • Stores “state of interest” to observers • Sends notification when state changes • ConcreteObserver • Implements updating interface

  22. observes Observer update() Subject For all x in observers{ x.update(); } attach (Observer) detach (Observer) notify () ConcreteObserver ConcreteSubject subject subjectState observerState setState() update() getState() observerState= subject.getState(); Observer Pattern - UML

  23. :ConcreteSubject :ConcreteObserver-1 :ConcreteObserver-2 setState() notify() update() getState() update() getState() Observer Pattern - Collaborations Observer Pattern, OOA&D, Rubal Gupta, CSPP, Winter ‘09

  24. TTTGame …… …… Observer Pattern in Java Swing «interface» ActionListener JFrame GameListener actionPerformed() * Observer Observable / Subject

  25. The MVC pattern • MVC stands for Model-View-Controller • The Model is the actual internal representation • The View (or a View) is a way of looking at or displaying the model • The Controller provides for user input and modification • These three components are usually implemented as separate classes

  26. Model View Controller (MVC) • The intent of MVC is to keep neatly separate objects into one of three categories • Model • The data, the business logic, rules, strategies, and so on • View • Displays the model and usually has components that allows user to edit change the model • Controller • Allows data to flow between the view and the model • The controller mediates between the view and model

  27. Model • The Model's responsibilities • Provide access to the state of the system • Provide access to the system's functionality • Can notify the view(s) that its state has changed

  28. View • The view's responsibilities • Display the state of the model to the user • At some point, the model (a.k.a. the observable) must registers the views (a.k.a. observers) so the model can notify the observers that its state has changed

  29. Controller • The controller's responsibilities • Accept user input • Button clicks, key presses, mouse movements, slider bar changes • Send messages to the model, which may in turn notify it observers • Send appropriate messages to the view • In Java, listeners are controllers

  30. Combining Controller and View • Sometimes the Controller and View are combined, especially in small programs • Combining the Controller and View is appropriate if they are very interdependent • The Model should still be independent • Never mix Model code with GUI code!

  31. Architecture Diagram Model business logic Set State GetState Update Event ChangeView View model representation Controller user interaction UserActions

  32. MVC Misunderstood • MVC is understood by different people in different ways • It is often misunderstood, but most software developers will say it is important; powerful • Lets start it right: • MVC is a few patterns put together

  33. Smalltalk-80™ • In the MVC paradigm, the user input, the modeling of the external world, and the visual feedback to the user are explicitly separated and handled by three types of objects, each specialized for its task. • The view manages the graphical and/or textual output to the portion of the bitmapped display that is allocated to its application. • The controller interprets the mouse and keyboard inputs from the user, commanding the model and/or the view to change as appropriate. • The model manages the behavior and data of the application domain, responds to requests for information about its state (usually from the view), and responds to instructions to change state (usually from the controller).

  34. Smalltalk-80™continued • The formal separation of these three tasks is an important notion that is particularly suited to MVC Smalltalk-80 where the basic behavior can be embodied in abstract objects: View, Controller, Model, and Object • MVC discovered by Trygve Reenskaug in 1979

  35. Sun says • Model-View-Controller ("MVC") is the recommended architectural design pattern for interactive applications • MVC organizes an interactive application into three separate modules: • one for the application model with its data representation and business logic, • the second for views that provide data presentation and user input, and • the third for a controller to dispatch requests and control flow.

  36. Sun continued • Most Web-tier application frameworks use some variation of the MVC design pattern • The MVC (architectual) design pattern provides a host of design benefits

  37. MVC Benefits • Clarity of design • easier to implement and maintain • Modularity • changes to one doesn't affect other modules • can develop in parallel once you have the interfaces • Multiple views • games, spreadsheets, powerpoint, Eclipse, UML reverse engineering, ….

  38. Summary (MVC) • The intent of MVC is to keep neatly separate objects into one of tree categories • Model • The data, the business logic, rules, strategies, and so on • View • Displays the model and often has components to allow users to change the state of the model • Imagine pressing arrow on a HuntTheWumpus view Demo JeyPressed • Controller • Allows data to flow between the view and the model • The controller mediates between the view and model

  39. Model • The Model's responsibilities • Provide access to the state of the model • getters, toString, other methods that provide info • Provide access to the system's functionality • changeRoom(int), shootArrow(int) • Notify the view(s) that its state has changed // If extending Java’s Obervable class, do NOT forget // to tell yourself your state has changed super.setChanged(); // Otherwise, the next notifyObservers message will not // send update messages to the registered Observers this.notifyObservers();

  40. View • The view's responsibilities • Display the state of the model to users, accept input • The model (a.k.a. the Observable) must register the views (a.k.a. Observers) so the model can notify the observers that its state has changed • Java’s Observer/Observable support provides public void addObserver(Observer o) // Adds an observer to the set of observers for this // object, provided that it is not the same as some // observer already in the set.

  41. Controller • The controller's responsibilities • Respond to user input (events) • Button click, key press, mouse click, slider bar change • Send messages to the model, which may in turn notify it observers • Send appropriate messages to the view • In Java, controllers are implemented as listeners • An ActionListener object and its actionPerformed method is a Controller

  42. MVC in TicTacToe Game TextFieldView row _ _ O _ X _ column _ _ _ DrawingView ActionListener MouseListener Game

  43. A SimplifiedExample: The “Reverser” Program • In this program we combine the Controller and the View • Instead of the view observing the Model, the controller is associated with the Model and it takes care of updating the view. • The Model does the computation (reversing the string)

  44. ReverserGUI.java • A bunch of import statements, then... • public class ReverserGUI extends JFrame {ReverserModel model = new ReverserModel();JTextField text = new JTextField(30);JButton button = new JButton("Reverse"); public static void main(String[] args) {ReverserGUIgui = new ReverserGUI();gui.create();gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } ... create()...}

  45. The create method private void create() {setLayout(new GridLayout(2, 1)); add(text); add(button); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String s = text.getText(); s = model.reverse(s);text.setText(s); } }); pack();setVisible(true); }

  46. The model • public class ReverserModel { public String reverse(String s) {StringBuilder builder = new StringBuilder(s);builder.reverse(); return builder.toString(); }} Controller Model View

More Related