MVC模式用于应用程序的分层开发,分为模型、视图、控制器。模型表示一个存取数据的对象,可以带有逻辑,在数据发生变化时更新控制器;视图表示模型包含的数据的可视化;控制器作用在模型和视图上,控制数据流向模型对象,并在数据变化时更新视图,实现模型和视图的分离。
- 创建模型对象Student;
public class Student {
//学号
private int rollNo;
//姓名
private String name;
public Student(int rollNo, String name) {
this.rollNo = rollNo;
this.name = name;
}
public int getRollNo() {
return rollNo;
}
public String getName() {
return name;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public void setName(String name) {
this.name = name;
}
}
- 创建视图对象StudentView输出学生信息;
public class StudentView {
void printStudentDetails(String name, int rollNo){
System.out.println("Student: Name is " + name + ",Roll No:" + rollNo);
}
}
- 创建控制器对象StudentController存储数据到模型,更新视图;
public class StudentController {
private Student model;
private StudentView view;
public StudentController(Student model, StudentView view) {
this.model = model;
this.view = view;
}
void setStudentName(String name){
model.setName(name);
}
void updateView(){
view.printStudentDetails(model.getName(), model.getRollNo());
}
}
- 创建启动类,测试输出。
public class MVCInstance {
public static void main(String[] args) {
Student model = retrieveStudentFromDatabase();
StudentView view = new StudentView();
StudentController controller = new StudentController(model, view);
controller.updateView();
controller.setStudentName("John");
controller.updateView();
}
//模拟从数据库中读取数据
private static Student retrieveStudentFromDatabase() {
return new Student(10, "Kafka");
}
}