Design patterns deal with the way code is organized in a program. The main goal is to separate the UI programming from the business logic, and each design pattern does this in its own way. Another positive thing about following a design pattern is that the code is unlikely to become ‘spaghetti code,’ because the programmer now has parameters that they must work within when building their program.
The design pattern discussed here today is the MVC pattern. MVC stands for Model-View-Controller. This pattern is made up of three interconnected components and was originally designed for building desktop GUI applications. In today’s programming world, it’s used in many places such as mobile and web application development.
So, what do the three interconnected components that make up the Model-View-Controller design pattern do?
The model is responsible for handling the business logic of the program, and can also encompass things such as networking code, persistence code, parsing, extensions, and more.
The View handles anything related to user interface components. These are usually reusable. In the iOS ecosystem, an example of a view would be a UIButton. Views are updated by the Controller after the Controller has been notified of what data to use by the Model.
The Controller is a mediator between the Model and View. The Controller receives user input from the View, then updates the Model with the data received from the user input. After the Model is updated, it then notifies the Controller of the change, and the Controller then updates the View.
Here is a visual of how this all works together:
As you can see, the three components work together in a (somewhat) harmonious cycle. Remember, when using a design pattern, there are now parameters by which the programmer should aim to abide by. Of course, like everything in software, MVC is not perfect. One of its major flaws is that the Controller is responsible for so many things that it can quickly become a massive, cluttered mess.
The main idea behind this design pattern is separating the data (model), how the data is displayed (view), and what controls and manipulates the data (controller).
Example of MVC Using Swift: https://github.com/andrew-lundy/mvc