Sobes.tech
Junior — Middle

How would you design and build an application from scratch based on the MVC architecture?

sobes.tech AI

Answer from AI

To create an application based on the MVC (Model-View-Controller) architecture from scratch in Java, you need to divide the logic into three main components:

  • Model — responsible for data and business logic. This includes classes that work with data, such as entity objects and methods for database interaction.

  • View — responsible for displaying data to the user. This can be JSP, HTML pages, templates, or GUI components.

  • Controller — receives user requests, processes them, interacts with the model, and selects the view to display the result.

Example of a simple MVC application:

// Model
public class User {
    private String name;
    public User(String name) { this.name = name; }
    public String getName() { return name; }
}

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

// Controller
public class UserController {
    private User model;
    private UserView view;

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

    public void setUserName(String name) {
        model = new User(name);
    }

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

// Usage
public class MVCPatternDemo {
    public static void main(String[] args) {
        User model = new User("Ivan");
        UserView view = new UserView();
        UserController controller = new UserController(model, view);

        controller.updateView();

        controller.setUserName("Peter");
        controller.updateView();
    }
}

In a real application, MVC is often implemented using frameworks (for example, Spring MVC), where controllers handle HTTP requests, models are linked to databases, and views are web pages or templates.