Presentation is loading. Please wait.

Presentation is loading. Please wait.

CompSci 230 S Software Construction

Similar presentations


Presentation on theme: "CompSci 230 S Software Construction"— Presentation transcript:

1 CompSci 230 S1 2016 Software Construction
MVC

2 Agenda & Reading Topics: Reading Separation of concerns (SoC)
Separation of Model and View Separation of View and Logic Java’s MVC Architecture Examples: ListModel, ComboBoxModel, TreeModel and TableModel Reading Software Engineering – A practitioner’s Approach, Roger Pressman Chapter 8 Object Oriented Software Engineering Using UML, Patterns and Java Chapter 6 The Java Tutorial: How to use Models Lecture13

3 Separation of Concerns
How to deal with complexity in a system? Separation of concerns (SoC) Separate issues (break down large problems into pieces) and concentrate on one at a time Break a program into distinct features that overlap in functionality as little as possible Concern: a piece of a program, usually a feature or a particular program behavior Two Categories: Separate concerns into classes and methods Separate data from UI, and UI from application logic Lecture13

4 Modularity Complex systems can usually be divided into simpler pieces called modules Module: self-contained component of a system Has a well-defined interface to other modules Separates its interface from its implementation Modularity can be used on different levels: Classes that implement a well-defined interface Packages with classes and methods (and other types) Lecture13

5 Advantages of Modular Systems
Modular systems are systems that are composed of modules Easier to understand: when dealing with a module the details of other modules can be ignored (separation of concerns) Modules can be developed & maintained independently Separation of work: different teams for different modules Independent testing of modules Modules can be reused in several systems Modules can be replaced by other modules with the same interface Isolation between modules can prevent failure in one module to cause failure in other modules Lecture13

6 Spaghetti Code vs. Modular System
Haphazard connections, probably grown over time No visible cohesive groups High coupling: high interaction between random parts Understand it all or nothing Modular System High cohesion within modules Low coupling between modules Modules can be understood separately Interaction between modules is well-understood and thoroughly specified 10 parts, 13 connections 10 parts, 13 connections, 3 modules Lecture13

7 Separation of UI and Data
Use different classes for Model and View: Model: the data that is presented by a widget, i.e. the data storage implementation (classes & methods) View: the presentation of the data on the screen, i.e. the widgets that paint the data (classes & methods) The data of a GUI component may be represented using several model objects, e.g. for Displayed data (e.g. list items in JList: ListModel) Widget state (e.g. selections in JList: ListSelectionModel) Different Views Data represented in Lecture13

8 Advantages of Model-View Separation
Separation of concerns during development Model can be developed & maintained independently from view Well-defined interface between model and view makes sure that they can work together New possibilities for connecting models and views Model can be displayed in multiple views Models and views can be distributed Model concept is integrated with event notification Changes of the model trigger updates of view Changes of the view trigger updates of model Consistency between model and view Model View Lecture13

9 A Typical Model-View Application
Many desktop applications provide multiple views of some data model. Invariant : all views should offer a mutually consistent representation of the model. JTable component instance Model JCombobox component Stats view Graphical view Change request Update notification Lecture13

10 Model-View in Swing Contemporary GUI frameworks, like Swing, are based on a separable model architecture All Swing widgets (JComponents) have separate models JTable << interface >> TableModel JComboBox << interface >> ComboBoxModel setValueAt( row, col ) JTree << interface >> TreeModel A Model can be thought of as a representation of a system, without concern for the details. For example, the ListModel would contain information about the items in the Jlist, without concern for how those items are shown. JTable component instance TableModel instance JList << interface >> ListModel tableChanged( event ) Lecture13

11 Separation of View and Logic
Use different classes for View and Applicatoin Logic: View: the presentation of the data on the screen, i.e. the widgets that paint the data (classes & methods) Logic: the that the program performs, e.g. decisions, calculations, data processing/filtering, etc. The logic of an application is implemented in your own classes Methods for the different operations triggered through the UI that read data from the model and work with it Should have a well-defined interface to view Main advantage: easier development & maintenance through separation of concerns Data triggers works with Logic Lecture13

12 you can modify or create views without affecting the underlying model
MVC Roles the model should not need to know about all the kinds of views and interaction styles available for it Model complete, self-contained representation of object managed by the application e.g., spreadsheet document provides a number of services to manipulate the data e.g., recalculate, save computation and persistence issues View tracks what is needed for a particular perspective of the data e.g., bar chart view presentation issues Controller gets input from the user, and uses appropriate information from the view to modify the model get slider value, trigger chart modify interaction issues you can modify or create views without affecting the underlying model Lecture13

13 Swing’s Model-based Architecture
Swing architecture is rooted in the model-view-controller (MVC) design that dates back to SmallTalk. MVC architecture calls for a visual application to be broken up into three separate parts: A model that represents the data for the application The view that is the visual representation of that data A controller that takes user input on the view and translates that to changes in the model.” [Amy Fowler, ibid.] Lecture13

14 Model-View-Controller (MVC)
refresh View Data display Controller User input UI: events refresh manipulate Model Data model Data: Lecture13

15 Example: C# TreeView Control
Controller treeView1.Nodes Nodes collection Model Lecture13

16 Example: Multiple Views
Controller View View Controller Model Lecture13

17 Example: C# DataBase Controls
DataGrid control -scroll, sort, edit, … View Controller DataSet class -tables -columns -rows DB Model Lecture13

18 Java MVC Architecture In Java, the View and Controller are generally combined into the same classes E.g. JComboBox provides an editor field View and Controls access data through a Data Model Each Model is defined as an Interface ComboBoxModel, ListModel, TableModel, ButtonModel Each GUI component comes with a default Model implementation DefaultComboBoxModel, DefaultListModel, DefaultTableModel Automatically propagate changes in the data to Views An abstraction that separates the access of the data from how it’s stored Lecture13

19 MVC Example in Java Example: JList
Example: PhilosophersJList.java <<interface>> Javax.swing.ListModel Javax.swing.JList Add/remove items notifies <<abstract>> AbstractListModel modifies DefaultListModel DefaultListModel Javax.swing.JComponent isEmpty(): boolean getSize(): int addElement(Object) removeElement(Object) elementAt(): Object removeElementAt(int) insertElementAt(int) indexOf(Object): int etc JList Example: JList A ListModel is an object which maintains a list of objects: it knows how big the list is, which object is where in the list, etc, and can insert/remove objects A JList is a graphical component giving a view of the list and able to receive user input to modify the list Lecture13

20 Creating a Model (List and Combo Box)
To create a list model: DefaultListModel — everything is pretty much taken care of for you. ListModel — create a new class which implements the ListModel interface and implement the getSize and getElementAt methods To create a combo box model: DefaultComboBoxModel — everything is pretty much taken care of for you. ComboBoxModel — create a new class which implements the ComboBoxModel interface and implement the setSelectedItem and getSelectedItem methods Lecture13

21 Example: MV_ComboBoxDemo.java
Examples Example: MV_ComboBoxDemo.java DefaultComboBoxModel: DefaultListModel: JComboBox<String> ppComboBox; ... DefaultComboBoxModel<String> cbm = new DefaultComboBoxModel<String>( new String[] { "person", "student", "employee" }); ppComboBox = new JComboBox<String>(cbm); creates a mutable list model object, puts the initial items in it, and uses the list model to create a list: JList<String> list; ... DefaultListModel<String> listModel = new DefaultListModel<String>(); listModel.addElement("red"); listModel.addElement("orange"); listModel.addElement("yellow"); list = new JList<String>(listModel); Lecture13

22 Tree Model TreeModel To create a tree model:
defines a suitable data model for a JTree key Concepts: root and children JTree get its data from an object that implements the TreeModel interface To create a tree model: DefaultTreeModel TreeModel — create a new class which implements the TreeModel interface and implements the following method … Object getRoot(): returns the root of the tree. Object getChild(Object parent, int index) : returns the child of parent at index in the parent's child array. int getChildCount(Object parent): returns the number of children of parent. int getIndexOfChild(Object parent, Object child): returns the index of child in parent. boolean isLeaf(Object node): returns true if node is a leaf. void removeTreeModelListener(TreeModelListener l) void valueForPathChanged(TreePath path, Object newValue) void addTreeModelListener(TreeModelListener l) Lecture13

23 Example: MV_TreeDemo.java
Adding Tree nodes: Create a JTree DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series"); DefaultMutableTreeNode category = new DefaultMutableTreeNode("Books for Java Programmers"); top.add(category); DefaultMutableTreeNode book = new DefaultMutableTreeNode("The Java Tutorial: A Short Course on the Basics"); category.add(book); book = new DefaultMutableTreeNode("The JFC Swing Tutorial: A Guide to Constructing GUIs"); JTree tree = new JTree(top); Lecture13

24 Using the TreeModel interface
Create a new class which implements the TreeModel interface and implements the 8 method … public class InfiniteBinaryTree implements TreeModel { public Object getRoot() { return 0; // return new Integer(0); } public int getChildCount(Object parent) { return 2; // because its a binary tree public Object getChild(Object parent, int index) { return index; public int getIndexOfChild(Object parent, Object child) { return (Integer) child; public boolean isLeaf(Object node) { return false; // an infinite number of internal nodes and no leaves! ... JTree binTree = new JTree(new InfiniteBinaryTree()); Lecture13

25 import java.swingx.table.*;
Using JTable Tables are used to display data in a spreadsheet fashion So key concepts in the model of a table: cell, row, column Value(s) in each Every table gets its data from an object that implements the TableModel interface You can use the DefaultTableModel, OR You an create a new class which implements the AbstractTableModel interface and implements the following methods: getColumnName getRowCount getColumnCount getValueAt import java.swingx.table.*; Lecture13

26 Using the DefaultTableModel
Example: DefaultTableModelDemo.java Model might hold its data in an array, vector or from an database Object[][] data = { {"Mary", "Campione","Snowboarding", new Integer(5) ...} {"Alison", "Huml","Rowing", new Integer(3), new Boolean(true)} ...}; String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"}; DefaultTableModel defaultTableModel = new DefaultTableModel(data, columnNames); ... table = new JTable(defaultTableModel); Lecture13

27 Using the AbstractTableModel
Example: AbstractTableModelDemo.java Steps in creating and using AbstractTableModel Create an AbstractTableModel subclass Implement the getRowCount() , getColumnCount() , and getValueAt() methods JTable table = new JTable(new AbstractTableModel() { public int getColumnCount() { return 10; } public int getRowCount() { return 10;} public Object getValueAt(int row, int col) { return new Integer(row*col); } }); getContentPane().add(table, BorderLayout.CENTER); Lecture13

28 Example: DefaultTableModelDemo.java
Controller Example: DefaultTableModelDemo.java A controller that takes user input on the view and translates that to changes in the model.” Example: You do NOT directly update JTable, T Instead, you update the TableModel, TM, which automatically updates the Table, T changeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DefaultTableModel tm = (DefaultTableModel) table.getModel(); for (int row=0; row<tm.getRowCount(); row++) { int years = (Integer) tm.getValueAt(row, 3); tm.setValueAt(years+1, row, 3); } }); Change the TableModel Lecture13

29 Example Update the ListModel
addButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { String name = JOptionPane.showInputDialog(PhilosophersJList.this, "Enter Name" ); philosophers.addElement( name ); } }); Change the ListModel removeButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { philosophers.removeElement(list.getSelectedValue() ); } }); Change the ListModel Lecture13

30 Summary: MVC Architecture
A typical application includes software to maintain application data, document text in a word processor state of a chess game -- positions of pieces present output outline view or print preview in a word processor graphical view of chess game process user input key presses mouse click on controls Lecture13


Download ppt "CompSci 230 S Software Construction"

Similar presentations


Ads by Google