Download 13MVC

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CompSci 230 S1 2016
Software Construction
MVC
Agenda & Reading

Topics:





Separation of concerns (SoC)
Separation of Model and View
Separation of View and Logic
Java’s MVC Architecture
Examples:


Reading

Software Engineering – A practitioner’s Approach, Roger Pressman



Chapter 8
Object Oriented Software Engineering Using UML, Patterns and Java

2
ListModel, ComboBoxModel, TreeModel and TableModel
Chapter 6
The Java Tutorial: How to use Models
Lecture13
Separation of Concerns

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:


3
How to deal with
complexity in a system?
Separate concerns into classes and methods
Separate data from UI, and UI from application logic
Lecture13
Modularity

Complex systems can usually be divided into simpler pieces called
modules

Module: self-contained component of a system



Modularity can be used on different levels:



4
Has a well-defined interface to other modules
Separates its interface from its implementation
Classes that implement a well-defined interface
Packages with classes and methods (and other types)
…
Lecture13
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





5
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
Spaghetti Code vs. Modular System

Spaghetti Code





Haphazard connections, probably grown over time
No visible cohesive groups
High coupling: high interaction between random
parts
10 parts, 13 connections
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
10 parts, 13 connections,
and thoroughly specified
3 modules
6
Lecture13
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)
Data
7
represented in
Different Views
Lecture13
Advantages of Model-View Separation

Separation of concerns during development



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



8
Model can be developed & maintained independently from view
Well-defined interface between model and view makes sure that they can
work together
Changes of the model trigger updates of view
Changes of the view trigger updates of model
Consistency between model and view
View
View
Model
View
View
Lecture13
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.
Graphical view
JTable component
instance
Model
Change
request
Stats view
Update notification
9
JCombobox component
instance
Lecture13
Model-View in Swing


Contemporary GUI
frameworks, like Swing, are
based on a separable model
architecture
All Swing widgets
(JComponents) have separate
models
setValueAt( row, col )
JTable component
instance
TableModel
instance
tableChanged( event )
10
JTable
<< interface >>
TableModel
JComboBox
<< interface >>
ComboBoxModel
JTree
<< interface >>
TreeModel
JList
<< interface >>
ListModel
Lecture13
Separation of View and Logic

Use different classes for View and Applicatoin Logic:

View: the presentation of the data on the screen,


Logic: the that the program performs,


i.e. the widgets that paint the data (classes & methods)
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
works
with
triggers
11
Logic
Data
Lecture13
the model should not need to know about all the
kinds of views and interaction styles available for it
MVC Roles

Model

complete, self-contained representation of object managed by the application


provides a number of services to manipulate the data



computation and persistence issues
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


12
e.g., recalculate, save
you can modify or create
views without affecting the
underlying model
View


e.g., spreadsheet document
get slider value, trigger chart modify
interaction issues
Lecture13
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.]
13
Lecture13
Model-View-Controller (MVC)
UI:
refresh
View
Data display
Controller
events
refresh
Data:
14
User input
manipulate
Model
Data model
Lecture13
Example: C# TreeView Control
TreeView control
View
Controller
treeView1.Nodes
Nodes collection
Model
15
Lecture13
Example: Multiple Views
View
Controller
View
Controller
Model
16
Lecture13
Example: C# DataBase Controls
DataGrid
control
-scroll, sort, edit,
…
View
Controller
DataSet class
DB
17
-tables
-columns
-rows
Model
Lecture13
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


Each GUI component comes with a default Model implementation



18
ComboBoxModel, ListModel, TableModel, ButtonModel
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
Example: PhilosophersJList.java
MVC Example in Java
Add/remove items
<<interface>>
Javax.swing.ListModel
<<abstract>>
AbstractListModel
DefaultListModel
Javax.swing.JComponent
JList

modifies
notifies
DefaultList
Model
Example: JList


19
isEmpty(): boolean
getSize(): int
addElement(Object)
removeElement(Object)
elementAt(): Object
removeElementAt(int)
insertElementAt(int)
indexOf(Object): int
etc
Javax.swing.
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
Creating a Model (List and Combo Box)

To create a list model:



To create a combo box model:


20
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
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
Example: MV_ComboBoxDemo.java
Examples

DefaultComboBoxModel:
JComboBox<String> ppComboBox;
...
DefaultComboBoxModel<String> cbm = new DefaultComboBoxModel<String>( new String[]
{ "person", "student", "employee" });
ppComboBox = new JComboBox<String>(cbm);

DefaultListModel:
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);
21
Lecture13
Tree Model

TreeModel




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 …








22
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
Example: MV_TreeDemo.java
Example
Adding Tree nodes:

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");
category.add(book);

Create a JTree
JTree tree = new JTree(top);
23
Lecture13
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());
24
Lecture13
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:




25
getColumnName
getRowCount
getColumnCount
getValueAt
import
java.swingx.table.*;
Lecture13
Example: DefaultTableModelDemo.java
Using the DefaultTableModel

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);
26
Lecture13
Example: AbstractTableModelDemo.java
Using the AbstractTableModel

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);
27
Lecture13
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
28
Lecture13
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
29
Lecture13
Summary: MVC Architecture

A typical application includes software to

maintain application data,



present output



outline view or print preview in a word processor
graphical view of chess game
process user input


30
document text in a word processor
state of a chess game -- positions of pieces
key presses
mouse click on controls
Lecture13