Design Patterns-MVC Pattern(譯)

原文連接java

譯者:smallclover設計模式

我的翻譯,水平有限,但願有所幫助mvc

設計模式-MVC模式

MVC設計模式 是Model-View-Controller 模式的表明(stand for)。該設計模式主要是用來分離(separate)應用的關注點(concerns)fetch

注:
Model:模型 View:視圖 Controller:控制器this

• Model - Model 表明一個對象(object)或者java普通對象(POJO)裝載的數據,若是它的數據發生變化,它也能夠有邏輯到update controller。spa

• View – View表明可視化模型所包含的數據。翻譯

• Controller - Controller 做用於model和view。它控制數據流向model對象,而且在數據發生改變的時候更新視圖,它保持者view和model的分離。設計

實現

首先咱們會建立一個Student對象來扮演model,StudentView將做爲一個view類,它能在控制檯輸出學生的詳細信息,StudentController 做爲一個controller 負責把數據存儲到student對象而且相應的更新view StudentViewcode

MVCPatternDemo,咱們的demo類,將使用StudentController來展現如何使用MVC模式htm

MVC Pattern

第一步

建立 Model

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

第二步

建立view

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

第三步

建立Controller

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) {

      //fetch student record based on his roll no from the database
      Student model  = retriveStudentFromDatabase();

      //Create a view : to write student details on console
      StudentView view = new StudentView();

      StudentController controller = new StudentController(model, view);

      controller.updateView();

      //update model data
      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
相關文章
相關標籤/搜索