Design patterns Model View Controller (MVC)


Example

1. What is MVC?

The Model View Controller (MVC) Pattern is a design pattern most commonly used for creating user interfaces. The major advantage of MVC is that it separates:

  • the internal representation of the application state (the Model),
  • how the information is presented to the user (the View), and
  • the logic which controls how the user interacts with the application state (the Controller).

2. Use cases of MVC

The primary use case for MVC is in Graphical User Interface (GUI) programming. The View component listens to the Model component for changes. The Model acts as a broadcaster; when there is a change mode to the Model, it broadcasts its changes to the View and the Controller. The Controller is used by the View to modify the Model Component.

3. Implementation

Consider the following implementation of MVC, where we have a Model class called Animals, a View class called DisplayAnimals, and a controller class called AnimalController. The example below is a modified version of the tutorial on MVC from Design Patterns - MVC Pattern.

/* Model class */
public class Animals {
    private String name;
    private String gender;

    public String getName() {
        return name;
    }

    public String getGender() {
        return gender;
    }

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

    public void setGender(String gender) {
        this.gender = gender;
    }
}

/* View class */
public class DisplayAnimals {
    public void printAnimals(String tag, String gender) {
        System.out.println("My Tag name for Animal:" + tag);
        System.out.println("My gender: " + gender);
    }
}

/* Controller class */
public class AnimalController {
     private Animal model;
     private DisplayAnimals view;

   public AnimalController(Animal model, DisplayAnimals view) {
      this.model = model;
      this.view = view;
   }

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

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

   public void setAnimalGender(String animalGender) {
      model.setGender(animalGender);        
   }

   public String getGender() {
      return model.getGender();        
   }

   public void updateView() {                
      view.printAnimals(model.getName(), model.getGender());
   }    
}

4. Sources used:

Design Patterns - MVC Pattern

Java SE Application Design With MVC

Model–view–controller