Senior
What is the MVC pattern?
sobes.tech AI
Answer from AI
The MVC (Model-View-Controller) pattern is an architectural template that divides an application into three components:
- Model — responsible for business logic and data. It stores the application's state and manages it.
- View — responsible for displaying data to the user. It receives information from the model and visualizes it.
- Controller — handles user input, interacts with the model, and updates the view.
This separation improves code maintainability and scalability, facilitates testing, and promotes component reuse.
Example in Java (simplified):
// Model
class User {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
// View
class UserView {
public void printUserDetails(String userName) {
System.out.println("User: " + userName);
}
}
// Controller
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.setName(name);
}
public void updateView() {
view.printUserDetails(model.getName());
}
}
This way, the controller manages the model and updates the view.