MVC Pattern
The MVC pattern stands for Model-View-Controller pattern. This pattern is used for layered development of applications.
Model - The model represents a data object or a JAVA POJO that accesses data. It can also contain logic to update the controller when the data changes.
View - The view represents the visualization of the data contained in the model.
Controller - The controller acts on both the model and the view. It controls the data flow into the model object and updates the view whenever the data changes. It keeps the view and the model separate.
Implementation
We will create a Student object as the model. StudentView is a view class that outputs the student details to the console, and StudentController is a controller class responsible for storing data into the Student object and updating the view StudentView accordingly.
MVCPatternDemo, our demo class, uses StudentController to demonstrate the usage of the MVC pattern.
Step 1
Create the model.
Student.java
public class Student {
private String rollNo;
private String name;
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Step 2
Create the view.
StudentView.java
public class StudentView {
public void printStudentDetails(String studentName, String studentRollNo){
System.out.println("Student: ");
System.out.println("Name: " + studentName);
System.out.println("Roll No: " + studentRollNo);
}
}
Step 3
Create the controller.
StudentController.java
public class StudentController {
private Student model;
private StudentView view;
public StudentController(Student model, StudentView view){
this.model = model;
this.view = view;
}
public void setStudentName(String name){
model.setName(name);
}
public String getStudentName(){
return model.getName();
}
public void setStudentRollNo(String rollNo){
model.setRollNo(rollNo);
}
public String getStudentRollNo(){
return model.getRollNo();
}
public void updateView(){
view.printStudentDetails(model.getName(), model.getRollNo());
}
}
Step 4
Use StudentController methods to demonstrate the usage of the MVC design pattern.
MVCPatternDemo.java
public class MVCPatternDemo {
public static void main(String[] args) {
// Retrieve student record from the database
Student model = retrieveStudentFromDatabase();
// Create a view: to print student details on the console
StudentView view = new StudentView();
StudentController controller = new StudentController(model, view);
controller.updateView();
// Update model data
controller.setStudentName("John");
controller.updateView();
}
private static Student retrieveStudentFromDatabase(){
Student student = new Student();
student.setName("Robert");
student.setRollNo("10");
return student;
}
}
Step 5
Execute the program, output result:
Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10