View
216
Download
0
Embed Size (px)
Citation preview
1
Model-View-ControllerModel-View-Controller
CS 236700: Software Design
Winter 2004-2005/T12
2
Graphical User InterfaceGraphical User Interface
Screenshot of a Jar file browser
3
FunctionalityFunctionality
Cells may be horizontally resized Affects all cells in the same type of table
Some cells display calculated valuesE.g.: “Signature” cells
Some cells display GUI-specific valuesE.g.: “Row”/”#” cells
Considering a single row:Each row displays information about a specific element
4
Inheritance: The problems (1/3)Inheritance: The problems (1/3)
A single table cell (see screenshot) may be classified as:Header Row vs. Data RowText vs. IconClickable vs. Non-clickableTable it belongs to: Types, Methods, FieldsType of information it shows: Row, Name, Static?
Clearly, such an environment cannot be modeled using single inheritanceA cell can only inherit one implementation for its methodsFor instance, who should be the super class of IconHeaderCell ?
Class IConCell
- Or - Class HeaderCell
5
Inheritance: The problems (2/3)Inheritance: The problems (2/3)
Multiple inheritance is more appropriate (in this context) , but has its drawbacks:Multiple inherited implementations: Concrete class must call
these implementations in the correct orderVirtual base class: a method (in super class A) can overwrite the
contents of a shared data memberMay break the invariants of super class B
Non-virtual base class: May lead to unreasonable duplication of dataFor instance, data member string text_ may appear
twice within a cell class• Which one is the “real” one?
6
Inheritance: The problems (3/3)Inheritance: The problems (3/3)
Things are even more complicated if we consider super classes which deal with non GUI concerns:Updating data structuresWriting data to files
7
Motivation (1/2)Motivation (1/2) The “old world”: Console applications
User had to choose an action from a menu Sometimes: Type in some data
A single flow of control: Menu -> Select action -> Invocation -> Menu …
Standard screen size (80x25), font, cursor => UI code (either Input or Output) was straightforward
The “new world”: Windowing New services: Drag and Drop, Splitters, Tooltips Operating System may interfere: Repaint, Show, Hide Variable window size, multiple fonts, cursors Many sources of input: Mouse, Keyboard, Menus, Toolbars User can invoke an action whenever he likes New actions: Close a window, Change focus, … Multithreading => UI code is more complicated than the domain-specific algorithms
8
Motivation (2/2)Motivation (2/2)
This “new world” creates a maze of methods and classes Code duplication Spaghetti structure Tight coupling
The solution: The Model-View-Controller (MVC) Pattern Provides separation of responsibilities in interactive programs At least, it is trying to…
9
Diagram: Ancient MVC Diagram: Ancient MVC
Model Encapsulates state and related algorithms
View Manages the visual display of the state held by the model
Controller Regulates the user interaction with the model
Direction of arrows may vary In the past, user input was delivered to dedicated objects
(We will discuss it again later)
Controller
Model
ViewInput Output
10
Diagram: Modern MVCDiagram: Modern MVC
In modern frameworks, GUI classes receive input events=> Controller methods are invoked by View code
Controller
Model
View Input/Output
11
ResponsibilitiesResponsibilities Model
Encapsulates application state Responds to state queries/updates Exposes application functionality
View Renders the model Allows Controller to select view Sends user input to the Controller
Controller Defines application behavior Maps user actions to Model updates Selects Views for response
12
MVC: ConsequencesMVC: Consequences
Support for different types of output (View)
The responses (Controller) are centrally located
Data structures (Model) can be seamlessly replaced
Tight coupling of View and Controller (when compared to View & Model, Controller & Model)
13
FlowFlow General flow of events:
1. View receives input
2. View calls Controller
3. Controller selects appropriate Model updates
4. Model updates corresponding data structures
5. Model notifies View of changes
-or -
5. Controller notifies View of changes
6. View queries Model
7. Model obtains requested data
8. View displays new output
14
MVC: Properties/CommentsMVC: Properties/CommentsMany variants
Some will be discussed in this lecture
Wide spectrum of applicabilityArchitecture of a complete applicationDesign of a single screen element
Responsibilities have changed over the yearsReflects the evolving languages and libraries
15
Design Patterns in ViewDesign Patterns in ViewComposite: When the output is structured as a hierarchy
of views, sub-views, sub-sub-views, …Typical in most applicationsMany times a plain, hard-coded tree will do
Decorator: Allow attachment of additional/modified behavior to an existing viewE.g.: a SelectMonth View can filter the data flowing into a ShowGraph view
Observer: Views are (typically) concrete observers of the ModelEach view extracts the data it needs when the application’s state
has changedSee: Active Model
16
Composite: intentComposite: intent
Compose objects into tree structures to represent part-whole hierarchies. Lets
clients treat individual objects and compositions of objects uniformly.
Compose objects into tree structures to represent part-whole hierarchies. Lets
clients treat individual objects and compositions of objects uniformly.
17
Relationships: View and GUI toolkitRelationships: View and GUI toolkitView can use an Abstract Factory to handle the creation
of new widgetsLocalizes the knowledge of the created typesApply initialization steps
Widgets with similar functionality can be made polymorphic by the Adapter patternE.g.: JList, JComboBox
Caution: The overhead (in development time) of these approaches is significantAdditional code must be written for each new widget we useSooner or later, someone will give up
18
Adapter: intentAdapter: intent
Convert the interface of a class into another interface clients expect.
Adapter lets classes work together that couldn't otherwise because of
incompatible interfaces.
Convert the interface of a class into another interface clients expect.
Adapter lets classes work together that couldn't otherwise because of
incompatible interfaces.
19
Model: Active vs. PassiveModel: Active vs. Passive Active
Model notifies View when its state has changed Usually through the observer pattern Model is aware of its role (in the MVC collaboration)
Passive Controller notifies View when model state has changed- Or - Controller instructs specific views/sub-views to reload data
Controller must know the side-effects of each user request => Even tighter coupling of View, Controller On the other hand, less “flickering” of the GUI due to non-
discriminating reload• Occurs when significant parts of the model are updated
In both cases, the Model is completely ignorant of the behavior of the Views, Controllers it is collaborating with
20
Design Patterns in ControllerDesign Patterns in ControllerStrategy
Each Controller may be a Strategy object used by the ViewChanging an assigned Controller allows the application to alter
its response
Command The update requests sent from the Controller to the Model can
be encapsulated as Command objectsThis provides the infrastructure for an undo/redo facilityAs a side effect, there is a single location for catching all
exceptions
21
MVC with Design PatternsMVC with Design Patterns
Command Observer
StrategyCompositeDecorator
Controller
Model
View Input/Output
Some non-frequent design patterns are not mentionedSuch as: Adapter, AbstractFactory (in View)
22
VVariantsariants
Let’s consider some alternatives… Many more are possible
23
Who receives the input?Who receives the input? The Controller Selection problem:
In the early days of MVC, user input was directly passed by the run-time system to a dedicated Controller object
(Inflicted by the design of GUI framework of SmallTalk80) This Controller was the one responsible for the main window
Consequently, the Controllers had to do a lot of work trying to figure out which specific controller should handle an incoming request
Obviously, an error-prone process
The modern approach, where GUI widgets also receive input events, delegates this responsibility to the run-time system
This makes the Controller selection problem a non-issue
Bottom line: In this case, high coupling is better than loose coupling (!)
24
Can Views maintain state ?Can Views maintain state ? A very tough questions. 1st Answer: “No”
Reason: All data should be maintained by the Model Problem: What about View specific data, such as:
Current page number in a page-up/down navigationPath to current node in a tree-like navigationKeeping this type of data in the model will make it
complicated, and (obviously) it is not needed when the GUI is changed
2nd answer: “Yes” Reason: View specific data (e.g.: page number) are not part of
the Model’s world of data Problem: Information that is kept inside the Views cannot be
controlled by the undo/redo mechanism, which is a pity
25
MultiplicityMultiplicity A single Controller vs. multiple controllers
The strategy pattern suggests that the program will define a controller for each request of the user
However, a program can have a single controller objectThe views will invoke Commands which will delegate
each request to the corresponding method on the Controller
Thus, Strategy can be replaced with Commands.
A single View vs. Multiple Views Multiple Views = Increased flexibility But, Multiple Views = Increased headaches
26
Additional problemsAdditional problems Concurrency
Typically, a background thread updates the Model These updates should be reflected on screen
=> Should go thru the “usual” path: Controller -> Model -> View Clearly, the obvious problems appear: Races, Dead Locks
Duplication of certain piece of the model To support “edit-apply/cancel” behavior
Loop-back problem1. Controller receives event2. Model state Changes (due to the Controller’s request)3. View reads new state4. New data is loaded into the screen widgets5. The widgets dispatch a “data-changed” event6. Controller receives event…