mvc 模式代表 model-view-controller(模型-视图-控制器) 模式。这种模式用于应用程序的分层开发。
我们将创建一个作为模型的 student 对象。studentview 是一个把学生详细信息输出到控制台的视图类,studentcontroller 是负责存储数据到 student 对象中的控制器类,并相应地更新视图 studentview。
mvcpatterndemo,我们的演示类使用 studentcontroller 来演示 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) {
//从数据可获取学生记录
student model = retrivestudentfromdatabase();
//创建一个视图:把学生详细信息输出到控制台
studentview view = new studentview();
studentcontroller controller = new studentcontroller(model, view);
controller.updateview();
//更新模型数据
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