Download presentation
Presentation is loading. Please wait.
Published byGriffin Chambers Modified over 9 years ago
1
2/3/20161
2
2
3
3
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. 2/3/20164
5
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 MVC – The Model 2/3/20165
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. 2/3/20166
7
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 MVC – The View 2/3/20167
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. 2/3/20168
9
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 MVC – The Controller 2/3/20169
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 2/3/201610
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 2/3/201611
12
12 User Input Update model Change in model Update view 2/3/201612
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 2/3/201613
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 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 2/3/201614
15
Separation of concern Allows re-use of business-logic across applications Allows development of multiple UIs without business logic Allows development of multiple UIs without business logic Discourages “cut-past” repetition of code, streamlining upgrade and maintenance tasks Discourages “cut-past” repetition of code, streamlining upgrade and maintenance tasks 2/3/201615
16
Developer specialization and focus UI developers can focus exclusive on UI without being bogged down in business logic rules 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 Business logic developers can focus on business logic without worrying about UI widgets 2/3/201616
17
Parallel Development teams Business logic developers can build “stub” classes that allow UI developers to forge ahead before business logic is fully implemented 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 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 Business rule changes are less likely to require revision of the UI 2/3/201617
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 2/3/201618
19
A DemoMVC Example 2/3/201619
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); } 2/3/201620
21
Controller // 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 //////////////////////////////////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 } 2/3/201621
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); } 2/3/201622
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. *@param 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. *@param 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(); } 2/3/201623
24
Another DemoMVC Example 2/3/201624
25
2/3/201625
26
Source code Model (see printout)printout View (see printout)printout Controller (see printout)printout Main (see printout)printout 2/3/201626
27
Pattern of Patterns 2/3/201627
28
2/3/201628
29
2/3/201629
30
2/3/201630
31
2/3/201631
32
2/3/201632
33
2/3/201633
34
2/3/201634
35
2/3/201635
36
2/3/201636
37
2/3/201637
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. 2/3/201638
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. 2/3/201639
40
2/3/201640
41
2/3/201641
42
2/3/201642
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.