MVC模式(Model-View-Controller Pattern)是一种软件架构模式,它将应用程序分为三个核心部分:模型(Model)、视图(View)和控制器(Controller)。
// 模型
public class Student {
private String name;
private String rollNo;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
}
// 视图
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);
}
}
// 控制器
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());
}
}