MVC Pattern


The Model View Controller Pattern splits the application into three parts, each with their purpose:
  • Model - carries data, and can have logic to update the controller if its data changes
  • View - the visualization of the data that the model contains.
  • Controller - acts on both model and view. Controls the data flow into the model and updates the view whenever data changes. It keeps the model and view separate.

MVC with Observer Pattern



The model should be an observable and all controllers should be in the model's observers list. The controllers talk directly to the model, and each controller/view pair can talk directly to eachother. The model doesn't directly talk to the controllers, just uses the notifyObservers( ) method on its observers list, to tell them that data has changed.

Communication in MVC

  1. Action on a view (example: button click) gets communicated to the controller.
  2. The controller translates that action to a method call on the model.
  3. If that method call is a request for data, then the model returns the data directly to the controller, which forwards it to the view.
  4. If that method call causes the model to change, the model notifies its observers.
  5. Each controller, being model observers, decides if the update is relevant to its view. If so, it calls the appropriate view methods.

Design principles (link):

  • (OK) Single Responsibility Principle - Each part of the program is designed around one part of the program's functionality. Model - system data, View - presentation and interaction with user, Controller - flow of data between view and model.
  • (OK) Open Closed Principle - Since the three parts are separated, it is easy to introduce new functionality in one part without changing the others. For example, we can add a new View without having to change the Model or the Controller

Relations with Other Patterns

  • We often use a Facade as bridge between the controller and the model in MVC.
  • MVC usually uses the Observer pattern to let the controller automatically update the view when the model notifies it of a change in its data.

Comments

Popular Posts