Junior — Middle
Explain the main difference between architectural patterns MVC and MVVM.
sobes.tech AI
Answer from AI
The main difference between MVC (Model-View-Controller) and MVVM (Model-View-ViewModel) lies in how the connection between the view and the interface logic is established.
-
MVC: The controller takes user input, updates the model, and then updates the view. The View and Controller are closely linked, and updating the View is usually done manually.
-
MVVM: The ViewModel acts as an intermediary between the View and the Model. The View binds to properties of the ViewModel through data binding, which allows the UI to update automatically when data changes without explicit update calls.
An example in C# using MVVM and data binding:
public class PersonViewModel : INotifyPropertyChanged
{
private string name;
public string Name
{
get => name;
set
{
if (name != value)
{
name = value;
OnPropertyChanged(nameof(Name));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
Here, the ViewModel notifies the View of changes, which simplifies data and UI synchronization.