Junior — Middle
Can you explain what the Model-View-Controller architectural pattern is?
sobes.tech AI
Answer from AI
Model-View-Controller (MVC) is an architectural pattern that divides an application into three main components:
- Model — responsible for data and business logic. It manages the application's state and interacts with the database.
- View — responsible for displaying data to the user, i.e., the user interface.
- Controller — accepts user input, processes it, interacts with the model, and updates the view.
This separation helps organize code, making it easier to maintain and extend the application.
Example: in a web application, a user clicks a button (View), the controller handles the event, requests data from the model, and then updates the interface.
// Simplified example
class Model {
public:
int data;
};
class View {
public:
void display(int data) {
std::cout << "Data: " << data << std::endl;
}
};
class Controller {
Model& model;
View& view;
public:
Controller(Model& m, View& v) : model(m), view(v) {}
void updateData(int newData) {
model.data = newData;
view.display(model.data);
}
};
int main() {
Model model;
View view;
Controller controller(model, view);
controller.updateData(42);
return 0;
}