A simple MVC (Model View Controller) implementation..code by Jimmy Chandra
http://stackoverflow.com/questions/1107720/mvc-c-simplest-possible-implementation
Why use MVC? Similar reasons to MVP - testability and seperation of concerns
Simple.MVC.zip (167.25 KB)
1. Program.cs runs, running Main.. as is standard in a Win Forms app. Difference from MVP is that main here is instantiating and running a controller class first of all, instead of newing up the view, which calls the controller/presenter.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
TopEmployeeController controller = new TopEmployeeController();
Application.Run(controller.View as Form);
}2. Controller is instantiated and constructor called:
private ITopEmployeeView _view;
private Employee _employee;
private bool _monitoring;
public TopEmployeeController()
{
_employee = new Employee();
_view = new TopEmployeeForm(this, _employee);
}
3. Controller news up an employee (dumb).. then a view of type TopEmployeeForm, passing its self (the controller) and employee to it.
4. View (the observer) subscribes to the model (the subject) so that when model.OnPropertyChange is called, view.UpdateView is called. This is the observer pattern, made easier in C# using events.. which is using a delegate.
// view
public TopEmployeeForm(ITopEmployeeController controller, Employee model)
{
_controller = controller;
_model = model;
//Let the model know that this view is interested if the model change
_model.OnPropertyChange += new Action(UpdateView);
InitializeComponent();
}
6. When Button is pressed on the view. The controller.GetTopEmplyee method is called. This calls model.MontorChanges:
// controller
public void GetTopEmployee()
{
if (!_monitoring)
{
_monitoring = true;
_employee.MonitorChanges();
}
}
7. MonitorChanges does some waiting code, then every second calls FirePropertyChange(). Which calls model.OnPropertyChange.
Which is really a delegate to View.UpdateView
// model
public event Action OnPropertyChange;
private void FirePropertyChange()
{
var propChange = OnPropertyChange;
if (propChange != null)
{
OnPropertyChange();
}
}
8. The view method which runs every second and displays the name on the form.
// view
public void UpdateView()
{
// to do with threading
if (this.InvokeRequired)
{
this.Invoke(new Action(UpdateView));
}
else
{
TopEmployeeName = _model.FullName;
}
}