MVC Pattern


MVC Pattern

Code can be downloaded from here

Introduction

MVC pattern is software design pattern. It separates the dependency between the actual business object and view so that different views and different business objects can interact independently. If you are not familiar with the term view you can consider it as the user interface (UI).  Avoiding the unnecessary coupling is really useful but difficult task in software architecture. MVC beautifully isolates the application logic from the UI introducing loose coupling and adding independent testing functionalities.

Motivation

  • Consider you like to display the certain set of data but in different UI. What should you do? If…else is of course not the good solution. Moreover, program should always tend to separate UI and Business Logic (BL). Let’s assume you manage to display the data in two different UI as user request. But two is not the end. What if your client wants to add certain other type of UI display? Now you will stuck if there is coupling between application data and user interface data. More there is the new UI requirement more complex will be your system.
  • Assume a web page.  A person can be good web page designer but it doesn’t mean he can understand complex business object.  But a programmer can understand the complex business object and he/she doesn’t need to understand about web rendering. Separation is necessary here so that two can work independently.

Architecture

Model

Model represents the core functionalities like data representation and processing. It processes the data behind the scene. In event-driven systems, the model notifies observers (usually views) when the information changes so that they can react.

View

It manages the display information. It renders the information from model into a form, suitable for user interaction.

Controller

It is the middle class between model and view. It contains both model and view and manage their interaction. It accepts input and passes the responsibilities to model and view as required.

Code

I want to give a very simple example of MVC model. You can find complete code here. There will be three different interfaces for model, view and controller and there will be two views which implements IView, two model which implements IModel and a controller which implements IModel. Consider the model interface IModel.


public interface IModel

{

List<Information> Informations { get; }

int HelloCount { get; }

void AddHello();

void RemoveHello();

void AddObserver(IView view);

void RemoveObserver(IView view);

void NotifyObservers();

}

In above interface Informations contains the data to display in view. I have used the Observer pattern to notify the views from model.

My view interface


public interface IView

{

void Show();

void SetUp(IModel model);

void Display(IModel model);

void ChangeRemoveState(bool state);

void ChangeAddState(bool state);

void AddHello();

}

It contains the SetUp function which sets the all three component and creates observer. The    most important function here is Display which accepts the IModel. It displays the information of model in UI. Note that there is interface in parameter so that it can accepts any class which implements IModel.

And my controller Interface.


interface IController

{

void SetModel(IModel model);

void SetView(IView view);

void RequestAddHello();

void RequestRemoveHello();

}

Consider one View, ListForm which implements the IView interface and display the information in ListView. It will not know what type of model. Its job is to just display the information of model. There are certain other functionalities which I added to show the program flow. For easy, I am not writing the designer code. Please, download code for complete solution.


public partial class ListForm : Form, IView

{

private IController _controller;

private IModel _model;

public ListForm()

{

InitializeComponent();

}

public void Display(IModel model)

{

listViewInformation.Items.Clear();

foreach (Information info in model.Informations)

listViewInformation.Items.Add(new ListViewItem(new string[] { info.Name, info.Address }));

}

public void AddHello()

{

_controller.RequestAddHello();

}

public void SetUp(IModel model)

{

if (_model != null)

_model.RemoveObserver(this);

_model = model;

_controller = new InformationControl(_model, this);

_model.AddObserver(this);

Display(_model);

}

public void Show()

{

ShowDialog();

Display(_model);

}

private void buttonAddHello_Click(object sender, EventArgs e)

{

_controller.RequestAddHello();

}

private void buttonRemoveHello_Click(object sender, EventArgs e)

{

_controller.RequestRemoveHello();

}

public void ChangeRemoveState(bool state)

{

buttonRemoveHello.Enabled = state;

}

public void ChangeAddState(bool state)

{

buttonAddHello.Enabled = state;

}

}

Whenever there is AddHello and RemoveHello call, it calls the controller to handle the request because we need to change the model accordingly.

I am writing code of a Model here. Please note that I have used abstract Model class which implements IModel. Whenever there are certain changes in Model it notifies the observer (view).


class FirstNameFirstModel : Model

{

public override List<Information> Informations

{

get

{

if (_informations == null)

{

_informations = new List<Information>(0);

foreach (XmlNode node in RootNode.ChildNodes)

{

Information info = new Information

{

Name = node.SelectSingleNode("//FirstName").InnerText + ", " + node.SelectSingleNode("//LastName").InnerText,

Address = node.SelectSingleNode("//Address").InnerText

};

_informations.Add(info);

}

}

return _informations;

}

}

public override void RemoveHello()

{

_helloCount--;

if (_helloCount < 0)

return;

Update();

}

public override void AddHello()

{

_helloCount++;

if (_helloCount > 10)

return;

Update();

}

private void Update()

{

string hello = string.Empty;

for (int i = 0; i < _helloCount; i++)

hello += "Hello ";

_informations = new List<Information>(0);

foreach (XmlNode node in RootNode.ChildNodes)

{

Information info = new Information

{

Name = hello + node.SelectSingleNode("//FirstName").InnerText + ", " + node.SelectSingleNode("//LastName").InnerText,

Address = node.SelectSingleNode("//Address").InnerText

};

_informations.Add(info);

}

NotifyObservers();

}

}

InformationControl class is used to behave as concreted controller.


class InformationControl : IController

{

private IModel _model;

private IView _view;

public InformationControl(IModel model, IView view)

{

_model = model;

_view = view;

}

public void SetModel(IModel model)

{

_model = model;

}

public void SetView(IView view)

{

_view = view;

}

public void RequestAddHello()

{

_model.AddHello();

UpdateState();

}

private void UpdateState()

{

_view.ChangeAddState(_model.HelloCount <= 10);

_view.ChangeRemoveState(_model.HelloCount > 0);

}

public void RequestRemoveHello()

{

_model.RemoveHello();

UpdateState();

}

}

Whenever there is update it calls UpdateState which decides the View’s UI status.

Conclusion

MVC model separates the application logic from UI so that two can vary independently and code becomes clean. Software design should be ‘Open for extension and close for extension’. MVC model greatly supports this principle by supporting any view and any model without actually changing the logic.

Next is What?

In my next article I will try to give you the overview of MVP model.

Advertisements

One thought on “MVC Pattern

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s