Introduction

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

  • Model – Model manages the app data and state. It is not concerned with UI or presentation.
  • 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.

The Model View Controller Pattern (MVC) is a compound pattern consisting of the Observer, Strategy and Composite patterns. The model makes use of the Observer Pattern so that it can keep observers updated yet stay decoupled from them.The controller is the strategy for the view. The view can use different implementations of
the controller to get different behavior. The view uses the Composite Pattern to implement the user interface, which usually consists of nested components like panels, frames and buttons.

Example

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

class StudentView 
{ 
  public void printStudentDetails(String studentName, String studentRollNo) 
  { 
    System.out.println("Name: " + studentName); 
    System.out.println("Roll No: " + studentRollNo); 
  } 
} 

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

class MVCPattern 
{ 
  public static void main(String[] args) 
  { 
    Student model = readData(); 

    StudentView view = new StudentView(); 

    StudentController controller = new StudentController(model, view); 

    controller.updateView(); 

    controller.setStudentName("Vikram Sharma"); 

    controller.updateView(); 
  } 

  private static Student readData() 
  { 
    Student student = new Student(); 
    student.setName("XYZ"); 
    student.setRollNo("5698"); 
    return student; 
  }
}