MVC模式表示:模型 - 檢視 - 控制器模式。此模式用於分離應用程式的問題。
在這個範例中,將建立一個作為模式的Student
物件. StudentView
將是一個可以在控制台上列印學生詳細資訊的檢視類,StudentController
是負責在Student
物件中儲存資料並相應地更新 StudentView
檢視的控制器類。
MVCPatternDemo
這是一個演示類,將使用StudentController
來演示MVC模式的使用。
MVC模式範例的結構如下圖所示 -
建立一個模型,其程式碼如下 -
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;
}
}
建立一個檢視,其程式碼如下 -
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);
}
}
建立一個控制器,其程式碼如下 -
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());
}
}
使用StudentController
方法來演示MVC設計模式的使用。
MVCPatternDemo.java
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);
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;
}
}
驗證輸出,執行上面的程式碼得到以下結果 -
Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10