MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application’s concerns.

  • Model – Model represents an object  carrying data. It can also have logic to update controller if its data changes.
  • View – View represents the visualization of the data that model contains.
  • Controller – Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate.

2000px-MVC-Process.svg.png

Implementation

We are going to create a student object acting as a model. StudentView will be a view class which can print student details on console and StudentController is the controller class responsible to store data in Student object and update viewStudentView accordingly.

MVCPatternDemo, our demo class, will use StudentController to demonstrate use of MVC pattern.

Capture.PNG

#include <iostream>
#include <string>
using namespace std;

        // STEP 1 --------------- Create Model 
class Student {

 int ClassNo;
 string name;

public:
      int getClassNo() {
        return ClassNo;
      }
public:
      void setClassNo(int cn) {
        ClassNo = cn;
      }
public:
      string getName() {
        return name;
       }
public:
      void setName(string n) {
        name = n;
      }
};
        // STEP 2 --------------- Create View
class StudentView {
public:
   void printStudentDetails(string studentName, int studentClassNo){
   cout << "Student: "<< endl << "Name : "<< studentName << endl << "ClassNo : "
        << studentClassNo << endl;
   }
};
        // STEP 3 --------------- Create Controller
class StudentController {
   Student model;
   StudentView view;

public:
  StudentController(Student m, StudentView v){
   model = m;
   view = v;
  }
public:
   void setStudentName(string name){
      model.setName(name);
   }
public:
   string getStudentName(){
     return model.getName();
   }
public:
   void setStudentClassNo(int ClassNo){
      model.setClassNo(ClassNo);
   }

public:
   int getStudentClassNo(){
    return model.getClassNo();
   }

public:
   void updateView(){
    view.printStudentDetails(model.getName(), model.getClassNo());
  }
};
  // STEP 4 Use the StudentController methods to demonstrate 
     MVC design pattern usage.
Student retriveStudentFromDatabase(){
 Student student;
 student.setName("Robert");
 student.setClassNo(1);
 return student;
}

void main() {

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

 StudentController controller(model, view);

 controller.updateView();

 //update model data
 controller.setStudentName("John");

 controller.updateView();

}

2.PNG
Advertisements