The MVC pattern stands for the Model-View-Controller (Model-View-Controller) pattern.
Model(模型) -the model represents an object or JAVA POJO that accesses data. It can also have logic to update the controller when the data changes.
View(视图) The view represents the visualization of the data contained in the model.
Controller(控制器) -controllers act on models and views. It controls the flow of data to model objects and updates the view when the data changes. It separates the view from the model.
As a model, we will create a Student Object. StudentView Is a view class that outputs student details to the console StudentController Is responsible for storing data to Student Object and update the view accordingly StudentView . MVCPatternDemo Our demo class uses the StudentController To demonstrate the use of MVC mode. Create a model. Create a view. Create a controller. Use StudentController Method to demonstrate the use of MVC design patterns. Execute the program and output the result:
6.28.1. Realize ¶
6.28.2. Step 1 ¶
Student.java ¶
publicclassStudent{privateStringrollNo;privateStringname;publicStringgetRollNo(){returnrollNo;}publicvoidsetRollNo(StringrollNo){this.rollNo=rollNo;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}}
6.28.3. Step 2 ¶
StudentView.java ¶
publicclassStudentView{publicvoidprintStudentDetails(StringstudentName,StringstudentRollNo){System.out.println("Student:");System.out.println("Name:"+studentName);System.out.println("Roll
No:"+studentRollNo);}}
6.28.4. Step 3 ¶
StudentController.java ¶
publicclassStudentController{privateStudentmodel;privateStudentViewview;publicStudentController(Studentmodel,StudentViewview){this.model=model;this.view=view;}publicvoidsetStudentName(Stringname){model.setName(name);}publicStringgetStudentName(){returnmodel.getName();}publicvoidsetStudentRollNo(StringrollNo){model.setRollNo(rollNo);}publicStringgetStudentRollNo(){returnmodel.getRollNo();}publicvoidupdateView(){view.printStudentDetails(model.getName(),model.getRollNo());}}
6.28.5. Step 4 ¶
MVCPatternDemo.java ¶
publicclassMVCPatternDemo{publicstaticvoidmain(String[]args){//从数据库获取学生记录Studentmodel=retrieveStudentFromDatabase();//创建一个视图:把学生详细信息输出到控制台StudentViewview=newStudentView();StudentControllercontroller=newStudentController(model,view);controller.updateView();//更新模型数据controller.setStudentName("John");controller.updateView();}privatestaticStudentretrieveStudentFromDatabase(){Studentstudent=newStudent();student.setName("Robert");student.setRollNo("10");returnstudent;}}
6.28.6. Step 5 ¶
Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10