13-MVC Pattern
13-MVC Pattern
Pattern
20/12/2013 1
Model-View-Controller Overview
A program can often be divided into two parts:
• "Model": the internal working "guts" of the
program where the processing actually takes
place.
• "View": the input and output of the program
which interacts with the user.
– The view takes the user input and passes the
information onto the model. The model outputs
information to the view, which then presents it to the
user.
20/12/2013 2
Model-View-Controller Overview
• In the spirit of "loose coupling" the following
ideals should be enforced:
– The model should operate independently from the
manner in which the view interacts with the user.
– The view should be tailored to meet the interaction
needs of the user, independent of the model below it.
– A model should work with a number of different views.
• Therefore, what we need is one more
component, the "Controller": "knows" about both
the specific model and specific view being used.
– The controller's job is: Takes user input from view
and figures out what it means to the model.
20/12/2013 3
Model-View-Controller architecture
• The Model-View-Controller ("MVC") design
pattern decouples the model from its view,
enabling loose coupling and the ability to change
one without affecting the other.
• MVC separates each application into three types
of component
– models for maintaining application data and
behaviors
– views for displaying all or a portion of the data,
– controllers for handling events that affect the model
or view(s).
20/12/2013 4
The model
• Holds all the data, state and application logic.
• It is built with no necessary concern for how it
will "look and feel" when presented to the user.
• It has a purely functional interface, meaning that
it has a set of public functions that can be used
to achieve all of its functionality.
20/12/2013 5
Views
• Provides graphical user interface (GUI)
components for a model and presentation of
information to the user.
• The view retrieves data from the model and
updates its presentations when data has been
changed in one of the other views.
• When a user manipulates a view of a model, the
view informs a controller of the desired change.
20/12/2013 6
Controllers
• Translates interactions with the view into actions
to be performed by the model.
– In a stand-alone GUI client, user interactions could be
button clicks or menu selections,
• The actions performed by the model include
activating business processes or changing the
state of the model.
– Based on the user interactions and the outcome of
the model actions, the controller responds by
selecting an appropriate view.
– These may cause changes to the information and in
turn trigger updates in all the views ensuring that they
are all up to date.
20/12/2013 7
MVC pattern: How It Works
20/12/2013 8
Implement MVC pattern
20/12/2013 9
Simple MVC
• In general, in order for a model and view to
communicate, an "adapter" object is needed to
translate the output of one into the input of the
other.
• The controller's job is:
– To instantiate both the model and the view.
– To instantiate the adapter(s) used to communicate
between the model and view.
– To establish the connections between the adapter
and the view and between the adapter and the
model.
20/12/2013 10
Simple MVC using Adapter
20/12/2013 11
Simple MVC
using Adapter
20/12/2013 12
Simple MVC Example
• Problem
– Your cousin has invited you to spend two weeks with
his family in Paris, France. Before you leave,
however, he warns you: "It's 35 degrees here!"
Remembering that France measures temperatures in
degrees Celsius, you frown... Does Your cousin want
you to pack your winter coat or your bathing suit?
• Converting Celsius to Fahrenheit and Back
public double convertFtoC(double degreesFahrenheit) {
return (degreesFahrenheit - 32.0) / 9.0 * 5.0;
}
public double convertCtoF(double degreesCelsius) {
return degreesCelsius / 5.0 * 9.0 + 32.0;
}
20/12/2013 13
Class
Diagram
20/12/2013 14
Implement TemCalcModel
public interface ITempCalcModel {
double convertFtoC(double degreesFahrenheit);
double convertCtoF(double degreesCelsius);
}
20/12/2013 15
Implement Adater
public interface IModelAdapter {
double FtoC(double degreesFahrenheit);
double CtoF(double degreesCelsius);
}
20/12/2013 17
MVC pattern structure
-controler:IControler
20/12/2013 18
MVC pattern structure
<<interface>>
<<interface>> Observable
Observer <<interface>> <<interface>>
IControler IModel
+register(o: Observer)
+update() +removeObserver(o: Observer)
+notifyObservers()
View Controler
Model
-controller: IController -model: Imodel
-model: Imodel -view: View
+register(o: Observer)
+update() +removeObserver(o: Observer)
+notifyObservers()
20/12/2013 19
MVC Example - MP3 player
Picture your favorite MP3 player (iTunes, ?)
• You can use its interface to add new songs,
manage play lists and rename tracks
• The player maintains
– Database of all your songs along with associated
names and data.
– Plays the song
– Updates the interface constantly with current song,
running time and so on
Underneath the covers --- Model View Controller
20/12/2013 20
Model View Controller
The view display is
updated for you. “Play new song”
You use the interface and your
You see the song actions go to the controller
display update and hear
the new song playing
Controller
Model
The model contains all the state, data, and
20/12/2013 application logic needed to maintain and play mp3s. 21
A Closer Look….
Lets see the nitty gritty details of how this MVC pattern works
VIEW: CONTROLLER: MODEL:
Gives you a Takes user input and The model holds all the data, state and
presentation of the figures out what it application logic. The model is
model. The view usually means to the model. oblivious to the view and controller,
gets the state and data although it provides an interface to
it needs to display manipulate and retrieve its state and it
directly from the model. can send notifications of state changes
to the Observer.
Controller
(1) The user did something (2) Change your state
class Player {
(3) Change your display play() {}
rip() {}
burn() {}
(4) I have changed }
View Model
(5) I need your state information
This is the user interface handles all application
data and logic.
20/12/2013 22
Observer
All these observers
Observers
Observable My state has changed will be notified
whenever state
class Foo {
void bar() {
changes in the model.
doBar();
}
}
View
Model
20/12/2013 23
Strategy
The controller is
The view the strategy for
delegates to the view -- it’s the
the controller The user did something object that knows
to handle the how to handle the
user actions. user actions.
Controller
View
20/12/2013 24
Composite
paint ()
View
20/12/2013 25
Example: Using MVC to control the beat…
• Time to be a DJ and start mixing with a beat!
• The Java DJ view:
20/12/2013 28
Putting the pieces together
20/12/2013 30
DJView
20/12/2013 31
Beat Controler
20/12/2013 32
Building the pieces
This gets called after the
BeatModel is instantiated.
This should look familiar, these We’ve split this into two kinds of observers:
methods allow objects to register observers that want to be notified on every beat,
as observers for state changes. and observers that just want to be notified with
the beats per minute changes.
20/12/2013 33
BeatModel class…. This is needed for the MIDI code.
20/12/2013 35
Implementing the View (just an outline!)
public class DJView implements ActionListener, BeatObserver, BPMObserver {
BeatModelInterface model;
ControllerInterface controller; DJView is an
JFrame viewFrame; observer for both the
The view holds a
JPanel viewPanel; reference to both the real-time beats and
BeatBar beatBar; model and the controller. BPM changes.
JLabel bpmOutputLabel;
public DJView(ControllerInterface controller, BeatModelInterface model) {
this.controller = controller;
this.model = model;
model.registerObserver((BeatObserver) this);
model.registerObserver((BPMObserver) this);
}
public void createView() { The updateBPM() method is called
// create all Swing components here when a state change occurs in the
} model. When that happens we update
public void updateBPM() { the display with the current BPM. We
int bpm = model.getBPM(); can get this value by requesting it
if (bpm == 0) { directly from the model.
bpmOutputLabel.setText("offline");
} else {
bpmOutputLabel.setText("Current BPM: " + model.getBPM());
}
} Likewise, the updateBeat() method is called
public void updateBeat() { when the model starts a new beat. When that
beatBar.setValue(100); happens, we need to pulse our “beatbar”. We do
} this by setting it to its maximum value and letting it
} 20/12/2013 handle the animation of the pulse. 36
The DJView continued…
public class DJView implements ActionListener, BeatObserver, BPMObserver {
BeatModelInterface model;
ControllerInterface controller;
Jlabel bpmLabel;
JTextField bpmTextField;
Jbutton setBPMButton, increaseBPMButton, decreaseBPMButton;
JMenuBar menuBar;
Jmenu menu; This method is called when
JMenuItem startMenuItem, stopMenuItem; a button is clicked.
public void createControls() {
// create all Swing components
}
public void actionPerformed(ActionEvent event) { If the Set button is
if (event.getSource() == setBPMButton) { clicked then it is
int bpm = Integer.parseInt(bpmTextField.getText()); passed on to the
controller.setBPM(bpm); controller along
} else if (event.getSource() == increaseBPMButton) { with the new bpm.
controller.increaseBPM();
} else if (event.getSource() == decreaseBPMButton) {
controller.decreaseBPM();
}
}
public void enableStopMenuItem ( ){ Likewise if increase or decrease
stopMenuItem.setEnabled(true); buttons are clicked, this information
} is passed on to the controller.
public void disableStopMenuItem ( ){
stopMenuItem.setDisabled (true);
}
} 20/12/2013 37
Now for the Controller….
• Remember - the controller is the strategy that we
plug into the view.
• What does a Strategy pattern look like? What do
we need?
public interface ControllerInterface Here are all the methods that a
view can call on the controller
{
void start();
void stop(); These should all look familiar after seeing the
void increaseBPM(); model’s interface. You can start and stop the beat
void decreaseBPM(); generation, and change the BPM. This interface is
“richer” than the BeatModel interface because you
void setBPM(int bpm); can adjust the BPMs with increase and decrease.
}
20/12/2013 38
public class BeatController implements ControllerInterface {
BeatModelInterface model;
DJView view; The Controller
The controller gets to hold
public BeatController(BeatModelInterface model) { on to the view and the model
this.model = model; and glues it all together.
view = new DJView(this, model);
view.createView();
view.createControls();
view.disableStopMenuItem();
view.enableStartMenuItem(); The controller is passed the model in the
model.initialize(); constructor and then creates the view.
}
public void start() {
model.on();
view.disableStartMenuItem();
view.enableStopMenuItem(); When you choose Start from the user interface
} menu, the controller turns the model on and then
public void stop() { alters the user interface to that the start menu item is
model.off(); disabled and the stop menu item is enabled.
view.disableStopMenuItem();
view.enableStartMenuItem();
}
public void increaseBPM() {
int bpm = model.getBPM();
model.setBPM(bpm + 1);
}
public void decreaseBPM() { Note: the controller is making the intelligent decision for
int bpm = model.getBPM(); the view.
model.setBPM(bpm - 1); The view just knows how to turn menu items on and off;
} it doesn’t know the situations in which it should disable
public void setBPM(int bpm) { or enable them.
model.setBPM(bpm);
}
20/12/2013
} 39
39
Putting it all together…
First create
public class DJTestDrive { the model…
public static void main(String[] args) {
BeatModelInterface model = new BeatModel();
ControllerInterface controller = new BeatController(model);
}
}
20/12/2013 40
the main MVC relationship is defined
by the Observer and Strategy patterns
• This is achieved by using the Observer design
pattern.
20/12/2013 41
the main MVC relationship is defined
by the Observer and Strategy patterns
• This View-Controller link is an example of the
Strategy design pattern.
20/12/2013 42
the main MVC relationship is defined
by the Observer and Strategy patterns
• Now we know that the Model acts as a Subject from the
Observer pattern and the View takes on the role of the
Observer object. In the other relationship of the MVC,
the View is a Context and the Controller is a Strategy
object.
20/12/2013 43
Summary
• The MVC Pattern is a compound pattern consisting of the
Observer, Strategy and Composite patterns.
• The model makes use of the Observer pattern so that it can
keep observers updated, yet stay decoupled from them.
• The controller is the strategy for the view.
The view can use different implementations of the controller to
get different behavior.
• The view uses Composite Pattern to implement the user
interface, which usually consists of nested components like
panels, frames, and buttons.
• These patterns work together to decouple the three players in
the MVC model, which keeps designs clear and flexible.
• The Adapter pattern can be used to adapt a new model to an
existing view and controller.
20/12/2013 44
BÀI TẬP
• Xây dựng giao diện cho người dùng thực hiện
thao tác chuyển đổi từ cơ số 10 (Dec) sang cơ
số hệ bát phân (Oct), hệ thập lục phân (Hex) và
hệ nhị phân (Bin). Áp dụng mẫu thiết kế MVC
observer/adapter để giải quyết bài toán trên. Với
màn hình giao diện chính như sau:
20/12/2013 45
Bài tập
• Khi chưa nhập số hệ cơ số 10 mà nhấn một
trong những button bên dưới, giao diện thông
báo như
Hình 1
Hình 2
Hình 4
Hình 3
20/12/2013 46
BÀI TẬP
• Xây dựng giao diện cho người dùng thực hiện
thao tác chuyển đổi từ cơ số 10 (Dec) sang cơ
số hệ bát phân (Oct), hệ thập lục phân (Hex) và
hệ nhị phân (Bin). Áp dụng mẫu thiết kế MVC
Strategy để giải quyết bài toán trên. Với màn
hình giao diện chính như sau:
20/12/2013 47
Bài tập
• Khi chưa nhập số hệ cơ số 10 mà nhấn một
trong những button bên dưới, giao diện thông
báo như
Hình 1
Hình 2
Hình 4
Hình 3
20/12/2013 48
BÀI TẬP _ Máy chẳn - 90 phút
• Xây dựng giao diện cho người dùng thực hiện
thao tác chuyển đổi từ cơ số 10 (Dec) sang cơ
số hệ bát phân (Oct), hệ thập lục phân (Hex) và
hệ nhị phân (Bin). Áp dụng mẫu thiết kế MVC
Adapter để giải quyết bài toán trên. Với màn
hình giao diện chính như sau:
20/12/2013 49
Bài tập
• Khi chưa nhập số hệ cơ số 10 mà nhấn một
trong những button bên dưới, giao diện thông
báo như
Hình 1
Hình 2
Hình 4
Hình 3
20/12/2013 50