0% found this document useful (0 votes)
6 views

13-MVC Pattern

The Model-View-Controller (MVC) pattern separates a program into three interconnected components: the Model (data and logic), the View (user interface), and the Controller (input handling). This architecture promotes loose coupling, allowing changes in one component without affecting others, and utilizes design patterns like Observer and Strategy for efficient communication and behavior management. The document also provides examples and outlines the implementation of the MVC pattern in various applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

13-MVC Pattern

The Model-View-Controller (MVC) pattern separates a program into three interconnected components: the Model (data and logic), the View (user interface), and the Controller (input handling). This architecture promotes loose coupling, allowing changes in one component without affecting others, and utilizes design patterns like Observer and Strategy for efficient communication and behavior management. The document also provides examples and outlines the implementation of the MVC pattern in various applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Model-View-Controller

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);
}

public class TempCalcModel implements ITempCalcModel {


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 15
Implement Adater
public interface IModelAdapter {
double FtoC(double degreesFahrenheit);
double CtoF(double degreesCelsius);
}

public class TempCalcApp {


public static void main(String[] args) {
final ITempCalcModel model = new TempCalcModel();
(new TempCalcView(new IModelAdapter() {
public double FtoC(double degreesFahrenheit) {
return model.convertFtoC(degreesFahrenheit);
}
public double CtoF(double degreesCelsius) {
return model.convertCtoF(degreesCelsius);
}
})).setVisible(true);
}
}
20/12/2013 16
MVC As An Aggregate Design Pattern
MVC is set of patterns together in the same design.
• Model uses Observer to keep views and controllers
updated on the latest state changes.
• View and Controller implement a Strategy Pattern
– Example: Controller is the behavior of the view and can be
easily exchanged with another controller if you want
different behavior.
• View also uses a pattern internally to manage the
windows buttons and other components of the
display => the Composite Pattern

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

View Controller manipulates


the model
class Player {
play() {}
The model notifies rip() {} Controller asks Player model
the view of a burn() {} to begin playing the song
change in its state. }

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

I’d like to register


as an observer
Controller View

The model has no dependencies on


viewers or controllers!

View Any object that’s interested in state changes in the


model registers with the model as an observer.

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

The view only worries about


presentation, the controller Controller
worries about translating user We can swap another
input to actions on the model. behavior for the view by
changing the controller.

20/12/2013 24
Composite
paint ()

The view is a composite


of GUI components
(labels, buttons, text
entry, etc.).

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:

A pulsing bar shows the beat in real time

A display shows the current BPMs and is


automatically set whenever the BPM changes.

The view has two


You can enter a specific
parts, the part for
BPM and click the Set button
viewing the state of the
to set a specific beats per
model and the part for
minute, or you can use the
controlling things.
increase and decrease
buttons for fine tuning.

Decreases the Increases the BPM by


BPM by one beat one beat per minute.
per minute.
20/12/2013 26
The Controller is in the middle…
• The controller sits between the view and the
model. It takes your input, like decreasing the
BPM and turns it into an action on the model to
decrease the BPM.
To control the DJView
You can start beat
kicking by choosing the
Start menu item in the
"DJ Control" menu All user actions are
sent to the controler
Notice Stop is disable
until you start the beat

The controler takes input


from the user and figures
out how to translate that into
requests on the model Controler
20/12/2013 27
Lets not forget the model underneath

The BeatModel is the heart of the


application. It implements the
logic to start and stop the beat,
set the beats per minute, and on()
generate the sound. off()
setBPM()
getBPM()

The model also allows us to


Beat Model
obtains its current state through
the getBPM( ) method.

20/12/2013 28
Putting the pieces together

Click on the beat


increase button

… which results in the


View controler being invoked

the controler asks the model


to update its BPM by one
Controller
You see the beatbar
pulse every 1/2 second
Because the BPM is 120, the view gets a on()
beat notification every 1/2 second off()
setBPM()
getBPM()
View is notified that the BPM changed. It
calls getBPM() on the model state
the view is updates Beat Model
to 120 BPM
20/12/2013 29
Beat Model

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.

These methods turn the


beat generator on and off.
public interface BeatModelInterface {
These are the void initialize();
methods that a void on(); This method sets the beats per
minute. After it is called, the beat
controller will use to void off();
frequency changes immediately.
direct the model based void setBPM(int bpm);
on user interaction.
The getBPM() method
int getBPM(); returns the current BPMs,
These methods allow void registerObserver(BeatObserver o); or 0 if the generator is off.
the view and controller
void removeObserver(BeatObserver o);
to get state and
become observers. void registerObserver(BPMObserver o);
void removeObserver(BPMObserver o);
}

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.

public class BeatModel implements BeatModelInterface, MetaEventListener {


Sequencer sequencer;
ArrayList beatObservers = new ArrayList(); The sequencer is the object that knows how to
ArrayList bpmObservers = new ArrayList(); generate the real beats (that you can hear!)
int bpm = 90;
// other instance variables
The ArrayLists hold the two kinds of Observers
public void initialize() {
setUpMidi(); bpm holds the frequency of beats. Default = 90.
buildTrackAndStart();
}
public void on() { This method does setup for the sequencer
sequencer.start(); and sets up the beat tracks for us.
setBPM(90);
} The on() and off ( ) starts and shuts off the
public void off() { sequencer.
setBPM(0);
sequencer.stop();
} (1) Sets the bpm instance variable
public void setBPM(int bpm) { (2) Asks the sequencer to change its beats
this.bpm = bpm;
sequencer.setTempoInBPM(getBPM()); (3) Notifies all BPM observers that the
notifyBPMObservers(); BPM has changed.
}
public int getBPM() {
return bpm;
} The beatEvent() method, which is not in the
void beatEvent() { BeatModelInterface, is called by the MIDI code
notifyBeatObservers ( );
} whenever a new beat starts. This notifies all
// code to register and notify observers BeatObservers that a new beat has just occurred.
20/12/2013
// Lots of MIDI code to handle the beat. 34
} 34
The view

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);
}
}

…then create a controller and pass it the


model. Remember, the controller creates the
view, so we don’t have to do that.

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

You might also like