Sobes.tech
Junior — Middle

Can you explain the main components of the Model-View-Controller architectural pattern?

sobes.tech AI

Answer from AI

The architectural pattern Model-View-Controller (MVC) divides an application into three main components:

  • Model: responsible for data and business logic. The Model stores the application's state and manages data, such as loading it from a database or API.

  • View: responsible for displaying data to the user. The View receives data from the Model and displays it, as well as responding to user input.

  • Controller: acts as an intermediary between the Model and the View. It handles user actions, updates the Model, and changes the View.

In iOS, for example, UIViewController often plays the role of the Controller, managing the interaction between the Model and the View.

Example:

class UserModel {
    var name: String
    init(name: String) {
        self.name = name
    }
}

class UserView {
    func displayUserName(_ name: String) {
        print("User name is: \(name)")
    }
}

class UserController {
    var model: UserModel
    var view: UserView

    init(model: UserModel, view: UserView) {
        self.model = model
        self.view = view
    }

    func updateUserName(to newName: String) {
        model.name = newName
        view.displayUserName(model.name)
    }
}

This separation simplifies support and extension of the application.