The best MVC pattern Tutorial In 2024, In this tutorial you can learn achieve,step 1,Step 2,Step 3,Step 4,Step 5,
MVC model represents the Model-View-Controller (Model - View - Controller) model. This mode is used for layered application development.
We will create aStudentobject model as.StudentViewis a student of the output to the console details viewclass,StudentController is responsible for storing the data to theStudentobject controller classes, and updates the viewStudentView.
MVCPatternDemo,we demonstrate the use ofStudentControllerclass to demonstrate the use of the MVC pattern.
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; } }
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); } }
Create 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 ()); } }
UseStudentControllermethod to demonstrate the use of the MVC design pattern.
MVCPatternDemo.java
public class MVCPatternDemo { public static void main (String [] args) { // Can obtain student records Student model = retriveStudentFromDatabase () from the data; // Create a view: the output to the console student details StudentView view = new StudentView (); StudentController controller = new StudentController (model, view); controller.updateView (); // Update model data controller.setStudentName ( "John"); controller.updateView (); } private static Student retriveStudentFromDatabase () { Student student = new Student (); student.setName ( "Robert"); student.setRollNo ( "10"); return student; } }
Verify output.
Student: Name: Robert Roll No: 10 Student: Name: John Roll No: 10