CHAPTER
27
MVC Design Pattern
This section describes MVC pattern and its implementation.
M VC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate
application's concerns.
Model - Model represents an object or JAVA POJO carrying data. It can also have logic
to update controller if its data changes.
View - View represents the visualization of the data that model contains.
Controller - Controller acts on both Model and view. It controls the data flow into model
object and updates the view whenever data changes. It keeps View and Model
separate.
Implementation
We're going to create Student object acting as a [Link] will be a view class which
can print student details on console and StudentController is the controller class responsible to
store data in Student object and update view StudentView accordingly.
MVCPatternDemo, our demo class will use StudentController to demonstrate use of MVC
pattern.
TUTORIALS POINT
Simply Easy Learning Page 121
Class Diagram
TUTORIALS POINT
Simply Easy Learning Page 122
Steps
Use the following steps to implement the above mentioned design pattern.
Step 1
Create Model.
[Link]
public class Student {
private String rollNo;
private String name;
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
[Link] = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
}
Step 2
Create View.
[Link]
public class StudentView {
public void printStudentDetails(String studentName, String
studentRollNo){
[Link]("Student: ");
[Link]("Name: " + studentName);
[Link]("Roll No: " + studentRollNo);
}
}
Step 3
Create Controller.
[Link]
public class StudentController {
private Student model;
private StudentView view;
public StudentController(Student model, StudentView view){
[Link] = model;
[Link] = view;
TUTORIALS POINT
Simply Easy Learning Page 123
}
public void setStudentName(String name){
[Link](name);
}
public String getStudentName(){
return [Link]();
}
public void setStudentRollNo(String rollNo){
[Link](rollNo);
}
public String getStudentRollNo(){
return [Link]();
}
public void updateView(){
[Link]([Link](), [Link]());
}
}
Step 4
Use the StudentController methods to demonstrate MVC design pattern usage.
[Link]
public class MVCPatternDemo {
public static void main(String[] args) {
//fetch student record based on his roll no from the
database
Student model = retriveStudentFromDatabase();
//Create a view : to write student details on console
StudentView view = new StudentView();
StudentController controller = new StudentController(model,
view);
[Link]();
//update model data
[Link]("John");
[Link]();
}
private static Student retriveStudentFromDatabase(){
Student student = new Student();
[Link]("Robert");
[Link]("10");
return student;
}
}
TUTORIALS POINT
Simply Easy Learning Page 124
Step 5
Verify the output.
Student:
Name: Robert
Roll No: 10
Student:
Name: Julie
Roll No: 10
TUTORIALS POINT
Simply Easy Learning Page 125