网站设计模式 专题
您的位置:web > 网站设计模式专题 > MVC 模式
MVC 模式
作者:--    发布时间:2019-11-20

mvc 模式代表 model-view-controller(模型-视图-控制器) 模式。这种模式用于应用程序的分层开发。

  • model(模型) - 模型代表一个存取数据的对象或 java pojo。它也可以带有逻辑,在数据变化时更新控制器。
  • view(视图) - 视图代表模型包含的数据的可视化。
  • controller(控制器) - 控制器作用于模型和视图上。它控制数据流向模型对象,并在数据变化时更新视图。它使视图与模型分离开。

实现

我们将创建一个作为模型的 student 对象。studentview 是一个把学生详细信息输出到控制台的视图类,studentcontroller 是负责存储数据到 student 对象中的控制器类,并相应地更新视图 studentview

mvcpatterndemo,我们的演示类使用 studentcontroller 来演示 mvc 模式的用法。

mvc 模式的 uml 图

步骤 1

创建模型。

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;
   }
}

步骤 2

创建视图。

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);
   }
}

步骤 3

创建控制器。

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());
   } 
}

步骤 4

使用 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;
   }
}

步骤 5

验证输出。

student: 
name: robert
roll no: 10
student: 
name: john
roll no: 10
网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册