mvc2 - School of Computer Science Student WWW Server

advertisement
Model-View-Controller (Part 2)
observer pattern, widgets, abstract model widgets
2
CS349 -- MVC
Recap and Observer Design Pattern
3
CS349 -- MVC
MVC Rationale
Multiple views, loosely coupled to the underlying data model.
4
CS349 -- MVC
Model-View-Controller (MVC)
Interface architecture decomposed into three parts:
– Model: manages the data and its manipulation
– View: manages the presentation of the data
– Controller: manages user interaction
View
Model
Controller
5
CS349 -- MVC
MVC Classes
Three classes: Model, View, Controller
• Model only knows about the View interface (below). Notifies
the view when its internal state changes.
• View and Controller both know all about the model.
View Interface
View
interface IView {
public void updateView();
}
Model
Controller
6
CS349 -- MVC
Theory and Practice
• MVC in Theory
– View and Controller both refer
to Model directly
– Model uses the observer design
pattern to inform view of
changes
• MVC in Practice
– Model is very loosely coupled
with UI using the observer
pattern
– The View and Controller are
tightly coupled
– Why?
• If the View and Controller are
tightly coupled, do we still need an
iView interface?
– Why not just have the controller
tell the view to update?
7
CS349 -- MVC
View
Model
Controller
View
Controller
Model
HelloMVC1 to HelloMVC4 Code Examples
HelloMVC1
1 view
HelloMVC2
2 (or more) views
Inner Class Approach
• Includes anonymous
inner classes, inner
classes, etc.
8
CS349 -- MVC
Observer Design Pattern
MVC is an instance of the Observer design pattern
• Provides a well-defined mechanism that allows objects to
communicate without knowing each others’ specific types
– Promotes loose coupling
• Related to
– “publish-subscribe” pattern
– “listeners”
– delegates in C#
• Implemented in
– java.util.Observer and java.util.Observable classes
9
CS349 -- MVC
Observer Design Pattern
subject
10
CS349 -- MVC
observer
MVC as Observer Pattern
subject
11
CS349 -- MVC
observer
HelloMVC4 Code Demo
• java.util provides Observer interface and Observable class
– Observer is like IView, i.e. the View implements Observer
– Observable is the “Subject” being observed
i.e. the Model extends Observable
– base class has list of Observers and method to notify them
12
CS349 -- MVC
Triangle Code Demos
• Program requirements:
– vary base and height of right triangle, display hypotenuse
• TriangleModel
– stores base and height, calculates hypotenuse
– constrains base and height values to acceptable range
13
CS349 -- MVC
Triangle: Main_1 and Main_2
Issues with SimpleTextView
• Precision of Hypotenuse
varies; sometimes wider
than the textbox.
• Hypotenuse can be edited
but that doesn’t change
the model.
• Tabbing or clicking out of
base or height doesn’t do
anything; must hit ‘Enter’.
SimpleTextView
TextView
14
CS349 -- MVC
Triangle: Main_3
Multiple Views
15
CS349 -- MVC
Triangle: Main_4
Graphical View
16
CS349 -- MVC
Triangle: Main_6
Graphical View
17
CS349 -- MVC
MVC – Practical Details
18
CS349 -- MVC
MVC Implementation Process
• Set up the infrastructure
– Create three or more empty classes:
• the model
• one or more view/controller classes (extends
JComponent or JPanel)
• a class containing the main method
– In the main method:
• create an instance of the model
• create instances of the views/controllers, passing
them a reference to the model
• display the view(s) in a frame
19
CS349 -- MVC
Hello MVC 1-4
hellomvc1 /
main.java
view.java
20
CS349 -- MVC
MVC Implementation Process (cont.)
• Build and test the model
– Design, implement, and test the model
•
•
add commands used by controllers to change the model
add queries used by the view to update the display
– Call updateAllViews just before exiting any public method
that changes the model’s data
• Build the Views and Controllers
– Design the UI as one or more views. For each view:
•
•
•
•
•
21
Construct widgets
Lay the widgets out in the view
Write and register appropriate controllers for each widget
Write updateView to get and display info from the model
Register updateView with the model
CS349 -- MVC
Apple “MVC” Pattern
• Apple IOS and Cocoa emphasize the Controller as an
intermediary link between the Model and View
• In my opinion, this is really a Model-View-Presenter (MVP)
Pattern (though lots of debate about this …)
(Presenter)
22
CS349 -- MVC
Part II: MVC at the Widget Level
23
CS349 -- MVC
Widget
Widget is a generic name for parts of an interface
that have their own behavior.
• e.g.: buttons, progress bars, sliders, drop-down
menus, spinners, file dialog boxes, …
• widgets also called “components”, or “controls”
• can have their own appearance
• receive and interpret their own events
• put into libraries (toolkits) for reuse
24
CS 349 - Widgets
Physical Input Devices
Lots of different mechanisms for capturing user
intent
• mechanical (e.g., switch, potentiometer)
• motion (e.g., accelerometer, gyroscope)
• contact (e.g., capacitive touch, pressure sensor)
• signal processing (e.g., computer vision, audio)
25
CS 349 - Widgets
Logical Input Device
Logical input devices are graphical components, defined by
their function (not what they looks like!)
Each device transmits a particular kind of input primitives:
• locator: inputs a (X,Y) position
• pick: identifies a displayed object
• choice: selects from a set of alternatives
• valuator: inputs a value
• string: inputs a string of characters
• stroke: inputs a sequence of (X,Y) position
There may be many physical devices (e.g., mouse,
keyboard, joystick, tablet) that can map to the same logical
input device.
26
CS 349 - Widgets
Logical Input Device
A widget can be considered a logical input device with
appearance.
Logical Button Device
– Model: none
– Events: generates a “pushed” event
– Appearance: can look like a push button, a keyboard
shortcut, a menu item
27
CS 349 - Widgets
Logical Input Device
A widget can be considered a logical input device with
appearance.
Logical Number Device
– Model: a number
– Events: “changed”
– Appearance: slider, spinner, textbox (with validation)
28
CS 349 - Widgets
MVC Widget Architecture
Properties
present
View
perceive
notify
essential
geometry
express
change
translate
29
CS 349 - Widgets
Model
Controller
logical device
Change
Events
MVC Widget Architecture
Note: We've now introduced
MVC at two distinct levels: the
widget and the entire application.
Widget
Properties
present
View
perceive
notify
essential
geometry
express
change
translate
30
CS 349 - Widgets
Model
Controller
Change
Events
Categorizing and Characterizing Widgets
• model the widget manipulates (number, text,
choice…)
• model implementation (simple, abstract)
• events the widget generates (action, change,
…)
• properties which change behaviour and
appearance (colour, size, icon, allowable
values, …)
• contains other widgets vs. stand-alone
31
CS 349 - Widgets
Simple Widgets 1
Labels and Images
– Model: none
– Events: Usually none
– Properties: text (font, size,…), image
– e.g. label, icon, spacer,
Button
– Model: none
– Events: push
– Properties: label, size, color, …
– e.g. button
Boolean
– Model: true/false
– Events: changed event,
– e.g. radio button, checkbox, toggle button
32
CS 349 - Widgets
“Radio Button”
33
CS 349 - Widgets
Simple Widgets 2
• Number
– Model: bounded real number
– Events: changed event,
– e.g. slider, progress bar, scrollbar
• Text
– Model: string
– Events: changed, selection, insertion
– Properties: optional formatters
(numeric, phone number, …)
– e.g. text fields, text areas,
34
CS 349 - Widgets
Special Value Widgets
Examples: colour/file/date/time pickers
35
CS 349 - Widgets
Container Widgets 1
• Panel (Pane, Form, Toolbar)
– arrangement of widgets
– e.g. JPanel, toolbar
• Tab
– choice between
arrangements of widgets
36
CS 349 - Widgets
Container Widgets 2
• Menu
– hierarchical list of
(usually) buttons
• Choice from a List
– list of boolean widgets
– e.g. drop-down, combobox, radio button group,
split button
37
CS 349 - Widgets
Simple Widgets
• Modern widget toolkits use MVC throughout
• Simple widgets usually contain a default model within
themselves
• Examples: buttons, checkboxes, scrollbars, ...
38
CS349 -- MVC
Example JButton
• In some ways, I believe that Java pushes MVC too far in UI
elements
– Consider JButton class (see Java documentation)
• JButton extends AbstractButton
• Check out Abstract Button
– Contains a ButtonModel to support state information,
listener information
– Contains methods (controller) to fireActionPerformed
– Contains an EventListenerList which contains a bunch of
EventListener descendants (see delaration in tab)
39
CS349 -- MVC
Abstract Model Widgets
• More complex widgets expect the application to
implement a model interface or extend an abstract class
• Examples: JTable and JTree
40
CS349 -- MVC
SimpleTable Demo Code
• Using default table model created by constructor:
– JTable table = new JTable(data, columnNames);
• Also shows use of scroll pane, with this pattern:
– JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
The sample code is
not a clean enough
design to emulate
for CS349!
41
CS349 -- MVC
TableModel Interface
public interface TableModel {
int getColumnCount();
String getColumnName(int columnIndex);
Class<?> getColumnClass(int columnIndex);
int getRowCount();
Object getValueAt(int rowIndex, int columnIndex);
void setValueAt(Object aValue, int rowIndex,
int columnIndex);
boolean isCellEditable(int rowIndex, int columnIndex);
void addTableModelListener(TableModelListener l);
void removeTableModelListener(TableModelListener l);
}
• AbstractTableModel provides
default implementations for
most of these …
42
CS349 -- MVC
Custom JTable using AbstractTableModel
• Need to implement 3 methods of AbstractTableModel
– public int getColumnCount();
– public int getRowCount() ;
– public Object getValueAt(int row, int col);
• Creates table of readonly columns with generic names, to
change this default behaviour, override:
– public String getColumnName(int col);
– public Class getColumnClass(int c);
– public boolean isCellEditable(int row, int col);
– public void setValueAt(Object value, int row, int col);
43
CS349 -- MVC
CustomTable Code Demo
• Inner table model class extended from AbstractTableModel
– only some columns are editable
– display Boolean type as checkbox
– sets column names
44
CS349 -- MVC
Firing Events in an AbstractTableModel
• Provides helper functions to fire events:
– void fireTableCellUpdated(int row, int column);
– void fireTableChanged(TableModelEvent e);
– void fireTableDataChanged();
– void fireTableRowsDeleted(int firstRow, int lastRow);
– void fireTableRowsInserted(int firstRow, int lastRow);
– void fireTableRowsUpdated(int firstRow, int lastRow);
– void fireTableStructureChanged();
45
CS349 -- MVC
MoreCustomTable Code Demo
• Even more customization with
– Custom TableCellRenderer
– Custom TableCellEditor
• Can change default cell renderer/editor by class or column
• Also sets tool tip for cell
• Uses JColorChooser dialog
46
CS349 -- MVC
Customization with TableColumnModel
• The TableColumnModel has methods like:
– void addColumn(TableColumn aColumn)
– TableColumn getColumn(int columnIndex)
– int getColumnCount()
– int[ ] getSelectedColumns()
– void moveColumn(int columnIndex, int newIndex)
– void setPreferredWidth(int preferredWidth)
– void setMinWidth(int minWidth)
– void setResizable(boolean isResizable)
– void setHeaderRenderer(TableCellRenderer
headerRenderer)
• More details about JTable customization here:
– http://docs.oracle.com/javase/tutorial/uiswing/components/ta
ble.html
47
CS349 -- MVC
48
CS349 -- MVC
Custom Control: OnPressButton
MVC Summary
49
CS349 -- MVC
MVC Rationale 1: Change the UI
• Separation of concerns enables alternative forms of
interactions with the same underlying data.
• Data and how it is manipulated (the model) will remain fairly
constant over time.
• How we present and manipulate that data (view and
controller) via the user interface will likely change more often
than the underlying model.
50
CS349 -- MVC
MVC Rationale 2: Multiple Views
• Separation of concerns enables multiple, simultaneous views
of the data.
• Given the same set of data, we may want to render it in
multiple ways:
– a table of numbers
– a pie chart
– a line graph
– an audio stream
– ...
• A separate model makes it easier for different UI components
to use the same data
– Each view is unencumbered by the details of the other
views
– Reduces dependencies on the GUI that could change
51
CS349 -- MVC
MVC Rationale 3: Code Reuse
• Separation of concerns enables programmers to more easily
use a stock set of widgets to manipulate their unique
application data.
• Example: JTable
– Because the model is separated out, it can be used to
manipulate many kinds of data stored in many different
ways.
– More time and attention can be given to JTable itself to
make it more robust and versatile.
52
CS349 -- MVC
MVC Rationale 4: Testing
• Separation of concerns enables one to more easily develop
and test data-specific manipulations that are independent of
the user interface
53
CS349 -- MVC
Download