Monday, January 10, 2011

MVC Pattern in Simple C#

MVC (Model View Controller) is an architectural pattern. In brief we can describe the participants as,
• A model is an object representing data and all other data service layers beneath it.
• A view is visualization of the state of the model.
• Controller facilities to change the state of the model.
MVC is consisting of Observer, Strategy, and Composite. It also uses Factory Method and Decorator, but the main MVC relationship is defined by the Observer and Strategy patterns.

The views and models use the Publish-Subscribe protocol (Observers Pattern) -when Model data is changed, it will update the View. View uses the Controller to implement a specific type of response (Strategy Pattern).The controller can be changed to let the View respond differently to user input

A simple representation of MVC in C# is as follows.

class Program
{
static void Main(string[] args)
{
var controller = new Controller();
IView view = controller.View;
view.Radius = "5";
view.UserEvent(view.Radius);
Console.WriteLine(view.Result);

Console.ReadLine();
}
}


public class Controller : IController
{
private IView _view;
private Model _model;


public IView View
{
get
{
return _view;
}
}

public Controller()
{
_model = new Model();
_view = new View(this, _model);
}

public void CalculateRadius(string radius)
{
_model.CalculateRadius(double.Parse(radius));
}
}



public interface IController
{
void CalculateRadius(string newModelState);
}


public interface IView
{
string Radius { get; set; }
string Result { get; set; }

void UserEvent(string radius);
}

public class Model
{
private object _modelState;

public event Action OnPropertyChange;

public Model()
{
}

public object ModelState
{
get
{
return _modelState;
}

set
{
_modelState = value;
NotifyPropertyChange();
}
}

private void NotifyPropertyChange()
{
var propChange = OnPropertyChange;
if (propChange != null)
{
OnPropertyChange();
}
}

internal void CalculateRadius(double radius)
{
ModelState = (Math.PI * radius*radius).ToString();
}

}

public partial class View : IView
{
private IController _controller;
private Model _model;

public View(IController controller, Model model)
{
_controller = controller;
_model = model;

//Let the model know that this view is interested if the model change
_model.OnPropertyChange += new Action(UpdateView);

}

string radius = string.Empty;
public string Radius
{
get { return radius; }
set { radius = value; }
}

string result = string.Empty;
public string Result
{
get { return result; }
set { result = value; }
}


public void UpdateView()
{
Result = _model.ModelState.ToString();

}

public void UserEvent(string radius)
{
_controller.CalculateRadius(radius);
}

No comments:

Post a Comment