MVC模式表示:模型 - 視圖 - 控制器模式。此模式用于分離應(yīng)用程序的問題。
在這個(gè)實(shí)例中,將創(chuàng)建一個(gè)作為模式的Student
對(duì)象. StudentView
將是一個(gè)可以在控制臺(tái)上打印學(xué)生詳細(xì)信息的視圖類,StudentController
是負(fù)責(zé)在Student
對(duì)象中存儲(chǔ)數(shù)據(jù)并相應(yīng)地更新 StudentView
視圖的控制器類。
MVCPatternDemo
這是一個(gè)演示類,將使用StudentController
來(lái)演示MVC模式的使用。
MVC模式示例的結(jié)構(gòu)如下圖所示 -
創(chuàng)建一個(gè)模型,其代碼如下 -
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;
}
}
創(chuàng)建一個(gè)視圖,其代碼如下 -
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);
}
}
創(chuàng)建一個(gè)控制器,其代碼如下 -
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
方法來(lái)演示MVC設(shè)計(jì)模式的使用。
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;
}
}
驗(yàn)證輸出,執(zhí)行上面的代碼得到以下結(jié)果 -
Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10