Presentation is loading. Please wait.

Presentation is loading. Please wait.

Model-View-Controller (MVC): Software Architecture Design Pattern

Similar presentations


Presentation on theme: "Model-View-Controller (MVC): Software Architecture Design Pattern"— Presentation transcript:

1 Model-View-Controller (MVC): Software Architecture Design Pattern
1/15/2019

2 1/15/2019

3 1/15/2019

4 Many facts about MVC A design pattern for the architecture of GUI applications. It works to separate data, UI and its control for a more cohesive and modularized system. Trygve Reenskaug formulated the MVC pattern for GUI design in 1979 while visiting the Xerox Palo Alto Research Center (PARC). Used in making Apple interfaces (Lisa and Macintosh). First used in the Smalltalk-80 framework. Implementation in Java can be found in Swing. Very popular, used extensively in Java and other languages. 1/15/2019

5 MVC – The Model Model represents data model
Manages behavior and data of application domain Classes in the system related to the internal representation of the state of the system often part of the model is connected to file(s) or database(s) examples (card game): Card, Deck, Player examples (bank system): Account, User, UserList 1/15/2019

6 Has methods to access and possibly update its contents.
Implements an interface which defines the allowed model interactions. An interface enables models to be pulled out and replaced without programming changes. 1/15/2019

7 MVC – The View View represents the screen(s) shown to the user
Manages the graphical and/or textual output to the display associated to its application Classes in the system that display the state of the model to the user GUI (could also be a text UI) should not contain crucial application data examples: PokerPanel, BankApplet 1/15/2019

8 There can be multiple views displaying the model at any one time.
Example, a companies finances over time could be represented as a table and a graph. Example: Bar chart vs. pie chart When the model is updated, all Views are informed and given a chance to update themselves. 1/15/2019

9 MVC – The Controller Controller represents interactions from the user that changes the data and the view Interprets the mouse and keyboard inputs from the user, commanding the model and/or the view to change as appropriate Classes that connect model and view defines how UI reacts to user input (events) receives messages from view (where events come from) sends messages to view/model (tells what data to display/update) sometimes part of view 1/15/2019

10 Users interact with the controller.
It interprets mouse movement, clicks, keystrokes, etc Communicates those activities to the model – eg: delete row, insert row, etc Interaction with the model indirectly causes the View(s) to update 1/15/2019

11 How do MVC work together?
User interacts with the VIEW UI CONTROLLER handles the user input (often a callback function attached to UI elements) CONTROLLER updates the MODEL and/or UI VIEW uses MODEL to generate new UI UI waits for user interaction 1/15/2019

12 User Input Update view Change in model Update model 1/15/2019 12

13 Should view and model interact directly?
No, allowing View to directly access Model creates a dependency Yes, on pure MVC, View talks directly with Model and vice-versa. Controller is only used when any change arises. Yes, controller is about user events, not model-to-view communication. In classical MVC, view observes model. Yes/No, MVC is only about separate Model-View-Control 1/15/2019

14 What are the benefits of MVC?
Separation of concerns in the code Developer specialization and focus Parallel development by separate team Makes it very easy to have multiple different displays of the same information (For example: a graph and a table could both display and edit the same data.) have different controls of the same view 1/15/2019

15 Separation of concern Allows re-use of business-logic across applications Allows development of multiple UIs without business logic Discourages “cut-paste” repetition of code, streamlining upgrade and maintenance tasks 1/15/2019

16 Developer specialization and focus
UI developers can focus exclusive on UI without being bogged down in business logic rules Business logic developers can focus on business logic without worrying about UI widgets 1/15/2019

17 Parallel Development teams
Business logic developers can build “stub” classes that allow UI developers to forge ahead before business logic is fully implemented UI can be changed as much as the customer requirements without slowing down the business logic development Business rule changes are less likely to require revision of the UI 1/15/2019

18 APIs: The Glue between Model, View, and Controller
Separation of concerns mean one layer does not care how another layer is implemented Each layer relies solely on the behaviors specified in the API of other layers The API specifies the behavior of the interface between a layer and the layers that interact with it. The APIs may be considered contracts to which each development team agrees before going off to implement the behavior promised by interface 1/15/2019

19 A DemoMVC Example 1/15/2019

20 Main // CalcMVC.java -- Calculator in MVC pattern. import javax.swing.*; public class CalcMVC { //... Create model, view, and controller. They are // created once here and passed to the parts that // need them so there is only one copy of each. public static void main(String[] args) { CalcModel model = new CalcModel(); CalcView view = new CalcView(model); CalcController controller = new CalcController(model, view); view.setVisible(true); } 1/15/2019

21 Controller //////////////////////////////////inner class MultiplyListener /** When a mulitplication is requested. * 1. Get the user input number from the View. * 2. Call the model to mulitply by this number. * 3. Get the result from the Model. * 4. Tell the View to display the result. * If there was an error, tell the View to display it. */ class MultiplyListener implements ActionListener { public void actionPerformed(ActionEvent e) { String userInput = ""; try { userInput = m_view.getUserInput(); m_model.multiplyBy(userInput); m_view.setTotal(m_model.getValue()); } catch (NumberFormatException nfex) { m_view.showError("Bad input: '" + userInput + "'"); } }//end inner class MultiplyListener // CalcController.java - Controller // Handles user interaction with listeners. // Calls View and Model as needed. import java.awt.event.*; public class CalcController { //... The Controller needs to interact with both the Model and View. private CalcModel m_model; private CalcView m_view; CalcController(CalcModel model, CalcView view) { m_model = model; m_view = view; //... Add listeners to the view. view.addMultiplyListener(new MultiplyListener()); view.addClearListener(new ClearListener()); } //////////////////////////////////inner class ClearListener /** 1. Reset model. * 2. Reset View. */ class ClearListener implements ActionListener { public void actionPerformed(ActionEvent e) { m_model.reset(); m_view.reset(); }// end inner class ClearListener The controller process the user requests. It is implemented here as an Observer pattern -- the Controller registers listeners that are called when the View detects a user interaction. Based on the user request, the Controller calls methods in the View and Model to accomplish the requested action. 1/15/2019

22 View // CalcView.java - View component // Presentation only. No user actions. import java.awt.*; import javax.swing.*; import java.awt.event.*; class CalcView extends JFrame { //... Constants private static final String INITIAL_VALUE = "1"; //... Components private JTextField m_userInputTf = new JTextField(5); private JTextField m_totalTf = new JTextField(20); private JButton m_multiplyBtn = new JButton("Multiply"); private JButton m_clearBtn = new JButton("Clear"); private CalcModel m_model; /** Constructor */ CalcView(CalcModel model) { //... Set up the logic m_model = model; m_model.setValue(INITIAL_VALUE); //... Initialize components m_totalTf.setText(m_model.getValue()); m_totalTf.setEditable(false); //... Layout the components. JPanel content = new JPanel(); content.setLayout(new FlowLayout()); content.add(new JLabel("Input")); content.add(m_userInputTf); content.add(m_multiplyBtn); content.add(new JLabel("Total")); content.add(m_totalTf); content.add(m_clearBtn); //... finalize layout this.setContentPane(content); this.pack(); this.setTitle("Simple Calc - MVC"); // The window closing event should probably be passed to the // Controller in a real program, but this is a short example. this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } void reset() { m_totalTf.setText(INITIAL_VALUE); String getUserInput() { return m_userInputTf.getText(); void setTotal(String newTotal) { m_totalTf.setText(newTotal); void showError(String errMessage) { JOptionPane.showMessageDialog(this, errMessage); void addMultiplyListener(ActionListener mal) { m_multiplyBtn.addActionListener(mal); void addClearListener(ActionListener cal) { m_clearBtn.addActionListener(cal); This View doesn't know about the Controller, except that it provides methods for registering a Controller's listeners. Other organizations are possible (eg, the Controller's listeners are non-private variables that can be referenced by the View, the View calls the Controller to get listeners, the View calls methods in the Controller to process actions). 1/15/2019

23 Model // CalcModel.java // Model // This model is completely independent of the user interface. // It could as easily be used by a command line or web interface. import java.math.BigInteger; public class CalcModel { //... Constants private static final String INITIAL_VALUE = "0"; //... Member variable defining state of calculator. private BigInteger m_total; // The total current value state. /** Constructor */ CalcModel() { reset(); } /** Reset to initial value. */ public void reset() { m_total = new BigInteger(INITIAL_VALUE); /** Multiply current total by a number. operand Number (as string) to multiply total by. */ public void multiplyBy(String operand) { m_total = m_total.multiply(new BigInteger(operand)); } /** Set the total value. value New value that should be used for the calculator total. public void setValue(String value) { m_total = new BigInteger(value); //====================================== getValue /** Return current calculator total. */ public String getValue() { return m_total.toString(); The model is independent of the user interface. It doesn't know if it's being used from a text-based, graphical, or web interface. This is the same model used in the presentation example. 1/15/2019

24 Another DemoMVC Example
This example application is a combination of the textbook's JList example (Figure 14.23) and the mouse drawing example using a JPanel (Figure 14.34). 1/15/2019

25 The following UML diagram shows unidirectional associations because, for example, DemoController has a DemoModel attribute, but not vice versa. A dependency is shown from DemoView to DemoController because DemoView's registerController method has a DemoController parameter. 1/15/2019

26 Source code Model (see printout) View (see printout)
Controller (see printout) Main (see printout) 1/15/2019

27 Pattern of Patterns 1/15/2019

28 1/15/2019

29 1/15/2019

30 1/15/2019

31 1/15/2019

32 1/15/2019

33 1/15/2019

34 1/15/2019

35 1/15/2019

36 1/15/2019

37 1/15/2019

38 What is software design pattern?
The idea of Design Patterns in software engineering grew out of work by Professor Christopher Alexander of UC Berkeley’s architecture department His ideas were applied to Software Engineering by authors of Design Patterns: Elements of Reusable Object-Oriented Software In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. 1/15/2019

39 Why should programmers care about Design Pattern?
It gives developers a common vocabulary to talk about software solutions. Designing applications in explicit conformity to design patterns facilitates the re-use of the insight and experience gleaned by the best and brightest developers over the course of thousands of real-world software development efforts. In short, Design Patterns will make you a better programmer and architect. 1/15/2019

40 1/15/2019

41 1/15/2019

42 1/15/2019


Download ppt "Model-View-Controller (MVC): Software Architecture Design Pattern"

Similar presentations


Ads by Google