Middle
245
What is the architectural pattern MVP?
Answer from AI
sobes.tech AI
The architectural pattern MVP (Model-View-Presenter) divides the application into three related parts:
- Model: Manages data and business logic. It is independent of the view.
- View: Displays data from the Model and intercepts user events. It contains no business logic, only display logic.
- Presenter: Acts as an intermediary between the Model and the View. It handles View events, requests data from the Model, formats it, and updates the View.
Key feature: The View is passive and does not know about the Model directly. The Presenter is responsible for interaction between them. The View is often implemented through an interface used by the Presenter.
Advantages:
- Better separation of responsibilities.
- Improved testability of the Presenter logic.
- View independence from business logic.
Disadvantages:
- May increase complexity for simple applications.
- Direct manipulation of the View from the Presenter can be less flexible compared to MVVM (where the View is bound to the ViewModel).
Example structure (simplified):
// Model
class User {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
// View (interface)
class IView {
displayUserName(name) {} // Method to display the name
}
// Concrete View (implementation)
class UserView extends IView {
constructor(elementId) {
super();
this.element = document.getElementById(elementId);
}
displayUserName(name) {
this.element.textContent = `Hello, ${name}!`;
}
}
// Presenter
class UserPresenter {
constructor(model, view) {
this.model = model;
this.view = view;
}
loadAndDisplayUser() {
const userName = this.model.getName();
this.view.displayUserName(userName);
}
}
// Usage
const userModel = new User("World");
const userView = new UserView('user-greeting');
const userPresenter = new UserPresenter(userModel, userView);
userPresenter.loadAndDisplayUser(); // Presenter updates the View
Comparison table with MVVM (partially):
| Attribute | MVP | MVVM |
|---|---|---|
| View management | Presenter directly manages the View | View is bound to the ViewModel |
| View testing | Difficult | Simplified (ViewModel is tested) |
| View dependency | On the Presenter | On the ViewModel |