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

Slides:



Advertisements
Similar presentations
Model-View-Controller Architecture Hector Raphael Mojica.
Advertisements

Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Graphical User Interface (GUI) Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Swing CS-328 Dick Steflik John Margulies. Swing vs AWT AWT is Java’s original set of classes for building GUIs Uses peer components of the OS; heavyweight.
Overview of Swing’s MVC Architecture By Geoffrey Steffens (BCSi), Socket Software, Australia Copyright © Socket Software, 2002.
Graphical User Interface (GUI) Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
Object-Oriented Analysis and Design
UNIT-V The MVC architecture and Struts Framework.
MVC pattern and implementation in java
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
Model View Controller (MVC) Rick Mercer with a wide variety of others 1.
Welcome to CIS 083 ! Events CIS 068.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
MVC CompSci 230 S Software Construction. MVC Architecture  A typical application includes software to  maintain application data,  document text.
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
(c) University of Washington08-1 CSC 143 Models and Views Reading: Ch. 18.
COMP 6471 Software Design Methodologies Winter 2006 Dr Greg Butler
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
3461 Model-View Controller Advanced GUI concepts.
Model View Controller (MVC) Bigger than a Pattern: It’s an Architecture Rick Mercer with help from many others 1.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
Model View Controller (MVC) Bigger than a Pattern: It’s an Architecture Rick Mercer with help from many of others 1.
Object-Oriented Programming (Java), Unit 28 Kirk Scott 1.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Computer Science 209 GUIs Model/View/Controller Layouts.
1 CSE 331 Model/View Separation and Observer Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia.
2/3/ 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.
Model View Controller (MVC) an architecture Rick Mercer with help from many of others 1.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
High degree of user interaction Interactive Systems: Model View Controller Presentation-abstraction-control.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Programming Paradigms, Software Architectural Patterns, and MVC CS 378 – Mobile Computing for iOS Dr. William C. Bulko.
A Quick Java Swing Tutorial
GUIs and Events Rick Mercer.
CSC 205 Programming II Lecture 5 AWT - I.
Design Patterns Source: “Design Patterns”, Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides And Created.
Graphical User Interfaces
A First Look at GUI Applications
“Form Ever Follows Function” Louis Henri Sullivan
GUIs Model/View/Controller Layouts
Review: Java GUI Programming
Lecture 27 Creating Custom GUIs
A Quick Java Swing Tutorial
Ellen Walker Hiram College
MVC Paradigm The MVC paradigm breaks applications or interfaces into three parts: the model, the view, and the controller. A --> 25 % B --> 60 % C -->
Chap 7. Building Java Graphical User Interfaces
Graphical User Interfaces -- Introduction
Course Outcomes of Advanced Java Programming AJP (17625, C603)
Model-View-Controller Patterns and Frameworks
Lecture 1: Multi-tier Architecture Overview
Starting Design: Logical Architecture and UML Package Diagrams
An Introduction to Software Architecture
Steps to Creating a GUI Interface
A Quick Java Swing Tutorial
Professor John Canny Spring 2004 March 5
Advanced Programming in Java
Events, Event Handlers, and Threads
Constructors, GUI’s(Using Swing) and ActionListner
Advanced ProgramMING Practices
Advanced ProgramMING Practices
Model, View, Controller design pattern
Professor John Canny Spring 2003 March 12
Presentation transcript:

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

1/15/2019

1/15/2019

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

A DemoMVC Example 1/15/2019

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

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

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

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(); 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

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

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

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

Pattern of Patterns 1/15/2019

1/15/2019

1/15/2019

1/15/2019

1/15/2019

1/15/2019

1/15/2019

1/15/2019

1/15/2019

1/15/2019

1/15/2019

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

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

1/15/2019

1/15/2019

1/15/2019