Middle
What is the architectural pattern MVP?
sobes.tech AI
Answer from AI
MVP (Model-View-Presenter) is an architectural pattern that divides an application into three interconnected parts: Model, View, and Presenter.
- Model: Contains data and business logic. It does not know about View and Presenter.
- View: Displays data from the Model and sends user actions to the Presenter. The View is "dumb" and does not contain business logic.
- Presenter: Acts as an intermediary between the Model and the View. It retrieves data from the Model, formats it, and passes it to the View for display. It also handles user actions from the View, processes them (possibly interacting with the Model), and updates the View. The Presenter knows about both the View and the Model.
Advantages of MVP:
- Improved separation of concerns.
- Increased testability (the Presenter can be tested independently of the View).
- Greater flexibility in changing the View, as the logic resides in the Presenter.
Differences from MVC (Model-View-Controller):
In MVP, the View does not directly interact with the Model. The Presenter takes on the role of the Controller from MVC, acting as an intermediary between the View and the Model. The View in MVP is passive and simply displays what the Presenter passes to it.
// Concept example:
class Model {
getData() {
return "Some data from Model";
}
}
class View {
displayData(data) {
console.log("Displaying in View:", data);
}
bindEvents() {
// Handling user actions and calling Presenter methods
}
}
class Presenter {
constructor(model, view) {
this.model = model;
this.view = view;
this.view.bindEvents(); // Subscribing View to events
}
loadData() {
const data = this.model.getData();
this.view.displayData(data);
}
// Methods to handle user actions from the View
handleUserAction() {
// ... logic
}
}
// Usage
// const model = new Model();
// const view = new View();
// const presenter = new Presenter(model, view);
// presenter.loadData();