What is MVC Architecture with an Exmaple

This blog post demonstrates MVC architecture, with an example in Java.

What is Model-View-Controller (MVC) Architecture?

The Model-View-Controller (MVC) architecture is a software design pattern that separates the application into three interconnected components. This separation helps manage complex applications, enabling efficient code reuse and parallel development. The Model component corresponds to all the data-related logic, the View component is used for all the UI logic, and the Controller acts as an interface between the Model and View components to process all the business logic and incoming requests, manipulate data using the Model component, and interact with the Views to render the final output.

Here's a brief overview of each component in the MVC architecture:

Model: 

This component represents the data and business logic of the application. It's responsible for accessing the database through CRUD (Create, Read, Update, Delete) operations and defining the business rules. The Model is the heart of the application because it represents the actual data or the state of the application. However, the Model does not concern itself with how data is presented to the user or how the user interacts with it.

View: 

The View component is all about presentation. It displays data (the Model) to the user and sends user commands (actions) to the Controller. The View is typically comprised of the UI elements such as text, dropdown menus, buttons, etc. It observes the Model but does not directly communicate with it, thus ensuring a separation of concerns.

Controller: 

Acting as an intermediary between the Model and the View, the Controller receives user input, processes it (sometimes involving changes to the Model), and returns the output display (View). It interprets the user's input, communicated through the View, into commands for the Model or View to act upon. This component controls the flow of data in the application and the interactions between the Model and the View.

Example of MVC Architecture using Java

Program Steps

1. Create the Model component to represent data and business logic.

2. Develop the View component to handle all the UI part.

3. Implement the Controller to act as an intermediary between Model and View, processing user inputs.

4. Demonstrate a simple interaction where user input is processed and reflected in the output.

Code Program

// Model Component
class UserModel {
    private String name;

    public String getName() {
        return name;
    }

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

// View Component
class UserView {
    public void printUserDetails(String userName) {
        System.out.println("User: " + userName);
    }
}

// Controller Component
class UserController {
    private UserModel model;
    private UserView view;

    public UserController(UserModel model, UserView view) {
        this.model = model;
        this.view = view;
    }

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

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

    public void updateView() {
        view.printUserDetails(model.getName());
    }
}

// Main class to demonstrate MVC Pattern
public class MvcExample {
    public static void main(String[] args) {
        // Creating the model
        UserModel model = retrieveUserFromDatabase();

        // Creating the view
        UserView view = new UserView();

        // Creating the controller
        UserController controller = new UserController(model, view);

        // Update the view using the controller
        controller.updateView();

        // Update the model data
        controller.setUserName("John Doe");

        // Update the view again to see the new data
        controller.updateView();
    }

    private static UserModel retrieveUserFromDatabase() {
        UserModel user = new UserModel();
        user.setName("Jane Doe");
        return user;
    }
}

Output:

User: Jane Doe
User: John Doe

Explanation:

1. The UserModel class represents the Model component containing the data (name) and the business logic (getters and setters in this simple example).

2. The UserView class represents the View component responsible for displaying the user details to the console.

3. The UserController class acts as the Controller, mediating the data flow between the Model and the View and controlling user interactions. It uses the Model to set or get user details and the View to display those details.

4. In the MvcExample main class, a UserModel object is created and populated with data (simulating data retrieval from a database). A UserView object is also created to display user details. Both are then passed to a UserController object.

5. The controller is first used to display the initial user details. Then, it updates the Model's user name and displays the new user details, demonstrating how changes in the Model are reflected through the View.

6. The output confirms the MVC architecture's functioning, showing the initial and updated user names as reflected by the View component after being modified by the Controller based on interactions with the Model.

Advantages of MVC Architecture

Separation of Concerns: By separating the application into three components, developers can work on individual components without affecting the others. This separation also makes the application more organized and manageable. 

Simplifies the Application: Making changes or adding new features becomes easier because the functional separation is clear. 

Facilitates Testing: Each component can be independently tested, which improves the quality of the application. 

Disadvantages of MVC Architecture

Complexity: For very simple applications, MVC might add unnecessary complexity. 

Learning Curve: Understanding how components interact within the MVC pattern might be challenging for beginners. 

Conclusion

MVC is a powerful architectural pattern widely used in web application development, including frameworks like ASP.NET MVC, Ruby on Rails, and Spring MVC. Its adoption can significantly enhance an application's structure and maintainability.

Comments