Model-View-Controller (MVC)
- Background
- MVC
is a software design pattern:
reusable solution to a commonly occurring problem
- Typically applied when implementing user interfaces
- First described
by Trygve Reenskaug in 1974 who was working on Smalltalk at Xerox PARC
- Several variations
like Model View ViewModel (MVVM)
which is often used in WPF and UWP
- Three components
Image from Wikipedia
- Model
- What your application is (not how it is displayed)
- Consists of application data and "business logic"
- Receives commands from the controller to update its state
- May notify its associated views and controllers when there has been a
change in its state
- View
- Visual representation of the model (what the user sees)
- Updates itself when the model indicates its state has changed
- Controller
- Accepts input (mouse, keyboard, etc.) and converts it into commands for the model
- May also send commands to the view to update itself
- MVC example: hTunes
- Controller (MainWindow.xaml.cs): User selects an MP3 to be added to the music library
- Model (MusicLib.cs): Controller tells the MusicLib class to add the MP3
- View (MainWindow.xaml): The controller tells the data grid to display the metadata for the MP3
which is obtained from the MusicLib
- Cloud architecture
- Benefits
- Achieves separation
of concerns where each part addresses a specific concern
- Interface modifications are largely isolated to the controller and view
- Multiple views and controls can be added in straightforward manner
- Model may be thoroughly tested without regards to UI
- Passive and active models for implementing MVC
- Passive model
Image from Model-View-Controller article
- Ideal when one controller manipulates the model exclusively
- Controller modifies the model and tells the View it needs to update itself
- View asks model for changes so it can update itself
- Typical model used in web applications where browser receives input and
transmits to the web server. Ajax or browser refresh used to get state changes from the server
- Active model
Image from Model-View-Controller article
- Used when model can change state without the controller's involvement
(e.g., outside source changing the data and views must reflect changes)
- Model notifies all registered views of changes instead of controller doing it
- Best implemented with Observer pattern
Image from Model-View-Controller article
- Each view implements the
Observer
interface and registers with the Model
- When the model changes, it iterates through all registered observers and
notifies them of the change
- Controllers may also be notified of changes if so desired
- See implementation
in C# which uses
IObservable
and IObserver
interfaces