MVC 模式代表 Model-View-Controller(模型-视图-控制器) 模式。这种模式用于应用程序的分层开发。
案例:
创建一个Model
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;
}
}
创建view
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);
}
}
创建controller
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());
}
}
测试
public class MVCPatternDemo {
//初始化
private static Student retrieveStudentFromDatabase(){
Student student = new Student();
student.setName("Robert");
student.setRollNo("10");
return student;
}
public static void main(String[] args) {
//创建一个model
Student model = retrieveStudentFromDatabase();
//创建一个视图:
StudentView view = new StudentView();
//管理 model 和 view
StudentController controller = new StudentController(model, view);
//把输出到控制台
controller.updateView();
System.out.println("\n\n--------------------------");
//更新model
controller.setStudentName("John");
//把输出到控制台
controller.updateView();
}
}
Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_45203607/article/details/120235574
内容来源于网络,如有侵权,请联系作者删除!