Skip to main content

MVC Design pattern

MVC stands for Model View Controller. This is a popular, and a useful design pattern. I'm coming up with simple explanations, for this very famous design pattern.

What is MVC?

If you breakdown any software, there will be 3 components in common :
1. Data (We are going to call it Model)
2. Interface to view or edit the data (View)
3. Functions that are performed on data (Controller)

Why MVC?

Any software is likely to be developed in a very dynamic way : in order to maintain re-usability.

Your client (or lecturer - who gave you the assignment/coursework maybe) might be adding modifications to the initial requirements, so that you will have to revise the code so many times. Even if the requirement is just a minor change, improper coding style might lead you to several changes that occur like a chain. 

Sometimes you might have to create the logic, whereas another person (or a team) is working on the UI. You will not know how will the UI look like until it is finalised, but you have to code the logic in the mean time. If you are used to implement the entire code inside the action event, that is got after double clicking the button or something (I'm referring to Java swing here), then you should either wait for the UI guy to complete work, or should be ready to do a Copy & Paste.

How can we reduce the effects of the above troubles? One answer would be, using MVC!

Sample Program

Let's try entering details of an employee in a Command Line Interfaced Java program, and displaying them back in CLI.

Let's capture the following details :
Registration Number, Name & Salary

For the above requirement, Someone can code like this:

import java.util.*;

public class EmployeeDetails{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);

    // get details

    System.out.println("Enter Reg No : ");
    String regNo = sc.nextLine();

    System.out.println("Enter Name : ");
    String name = sc.nextLine();

    System.out.println("Enter Salary : ");
    double salary = sc.nextDouble();

    // print details

    System.out.println("Reg No : "+regNo);
    System.out.println("Name : "+name);
    System.out.println("Salary : "+salary);
  }
}

Seems easy right?
Not at all!
Now, what if the requirement is changed as 'Get the details in CLI, and display as a GUI message'?
Are you going to change every System.out.println("TODO "+todoVariable) into someLabel.setText("TODO "+todoVariable) ?

It's ugly!

Let's use MVC!

1) 
Create Employee.java, which will be the Model (Data)

public class Employee{
private String regNo;
private String name;
privatae double salary;

public String getRegNo(){
return this.regNo;
}

public void setRegNo(String regNo){
this.regNo = regNo;
}

public String getName(){
return this.name;
}

public void setName(String name){
this.name = name
}

public double getSalary(){
return this.salary;
}

public void setSalary(double salary){
this.salary = salary
}
}

2) Create EmpView.javawhich will be the View

public class EmpView{
public void viewEmployee(String regNo, String name, double salary){
System.out.println("Employee No : " + regNo);
System.out.println("Employee Name : " + name);
System.out.println("Empoyee Salary : " + salary)
}
}

3) Create EmpController.javawhich will be the Controller

public class EmpController{

private Employee model;
private EmpView view;

public EmpController(Employee model, EmpView view){
this.model = model;
this.view = view;
}

public void setEmpName(String name){
model.setName(name);
}

public String getEmpName(){
return model.getName();
}

public void setEmpRegNo(String regNo){
model.setRegNo(regNo);
}

public String getEmpRegNo(){
return model.getRegNo();
}

public void setEmpSalary(double salary){
model.setSalary(salary);
}

public double getEmpSalary(){
return model.getSalary();
}

public void updateView(){
view.viewEmployee(model.getRegNo(), model.getName(), model.getSalary());
}
}

As you can see, the EmpController.java is the player here. We can call this guy to set data in Model, and produce outputs in View.

4) Create Main.java with main() method, which will run the program in MVC pattern.

public class Main{
public static void main(String[] args){
Employee model = getEmployee();
EmpView view = new EmpView();
EmpController controller = new EmpController(model,view);

controller.updateView();
}

// this can be returning a selected employee from a database
private static Employee getEmployee(){
// a hard coded employee instance
Employee employee = new Employee();
employee.setRegNo("EMP001");
employee.setName("Senthuran");
employee.setSalary(100000.0);
return employee;
}
}



This will give the following results, as the view is updated now :

Employee No : EMP001
Employee Name : Senthuran
Employee Salary : 100000.0

Try inserting the following code at the end of main() method to modify the data, and update the view again.

controller.setEmpSalary(150000);
controller.updateView();

Output :

Employee No : EMP001
Employee Name : Senthuran
Employee Salary : 150000.0

Remember I said about the requirement change :
'Get the details in CLI, and display as a GUI message'?
How to do that?
Just modify EmpView.java with Java Swing components. All the other things will remain the same.



Comments

  1. Simple clear explanation great work 👍

    ReplyDelete
  2. Excellent explanation 👍🏻 Thanks for sharing

    ReplyDelete
  3. very good explanation. Good job.really its useful.

    ReplyDelete
  4. job well done, superb explanation

    ReplyDelete
  5. Perfect Explanation!

    ReplyDelete

Post a Comment

Popular Posts

Time Complexity in Algorithms

When you are running an algorithm, it takes some time to run. If your computer is super fast, then your running time would be so tiny fractions of a second, but that time can not be absolute zero. We can call that time  as cost , since it's something like units. More running time, is more cost. You can't guarantee that, Your Computer with some tasks running in background, will take the same time as mine; with the same tasks running in background. It's dependant on both of our computers' CPU, Memory and so on. But I can tell that, my computer almost*  works in a similar manner, every time*. So I calculate that cost  and multiply it with some value for my computer, where as you can get that same cost  and multiply it by some other value for your computer. Calculating that cost,  is what we are about to do now. So if we are going to calculate the cost, the following things matter in a code. Statements Blocks Statements If you are using a l...

Introduction to Play Framework

Play Framework makes building web applications easier with Java & Scala. It is lightweight and in a web-friendly architecture. Play is a RESTful service by default, and built targeting modern web & mobile. REST stands for REpresentational State Transfer. For a great admiration, Linkedin uses Play framework in their infrastructure. We are going to create a simple Registration & login mechanism using Play Framework to understand about it. Note that we are not going to create a database or any permanent storages, so that your registration details can be used in login only until the current run is not stopped. 1. Setting up the environment I've used the following, in developing this login form Java Development Kit 1.8.0_121 ( http://www.oracle.com/technet work/java/javase/downloads/ index-jsp-138363.html ) IntelliJ IDEA 2016.3.3 ( https://www.jetbrains.com/ide a/#chooseYourEdition ) Scala plugin 2.12.1 installed ( https://www.scala-lang.org/download/ ) ...