The Model-View-Controller (MVC) is one of the classic architectural patterns from the book ““. It addresses interactive applications with a flexible human-machine interface.
The MVC divides the program logic of a user interface into separate components model, view, and controller. The model manages the data and rules of the application. The view represents the data, and the controller interacts with the user.
Model-View-Controller
Purpose
- User interfaces need to be changed frequently
- Different user interfaces must be supported
- The data model is stable
Solution
- The application is divided into the components Model (data model), View (output components), and Controller (input components)
- Multiple output components can use the same data model
Structure
Model
- The central component of the pattern
- Contains the data (and the business logic)
- Is independent of the
View
andController
View
- Is responsible for the representing of the data and user interaction
- Observes the
Model
- A
View
is associated with aController
to manipulate the Model
Controller
- Manages one or more
View
s - Accepts user interactions and prepares them for the
Model
orView
- Observes the
Model
- Implements the update logic
There are two exciting aspects of the MVC: initialization and user input:
Initialization
The following steps happen during the initialization of the MVC:
- The model is created, and it initializes its data
- The view is created and observes the Model
- The controller is created and gets references to the model and the view; it observes the model
- The application starts event processing
User Input
In case of a user event, the following steps happen:
- The controller accepts the user input, handles them, and triggers the model
- The model changes its internal data
- The model notifies all views and controllers about the change of the internal data
- The views and controller update themself
- If the PIN is entered incorrectly in an ATM for the third time, this can mean: The display shows that your account is locked. The ATM confiscates your debit card
- The controller continues to process events
Example
The following program mvc.cpp
applies the MVC.
// mvc.cpp #include#include #include class DefectModel { public: // (5) mutable std::unordered_map<std::string, std::string> defects_ = { {"XYZ" , "File doesn't get deleted."}, {"XAB" , "Registry doesn't get created."}, {"ABC" , "Wrong title get displayed."} }; std::string getDefectComponent(const std::string& component) const { return defects_[component]; } int getSummary() const { return defects_.size(); } std::unordered_map<std::string, std::string> getAllDefects() const { return defects_; } }; class DefectView { public: void showSummary(int num) con