Introduction to Model View Control (MVC) Pattern using C#

Benefits

The benefits of using the Model-View-Control (MVC) pattern in our development projects is that we can completely decouple our business and presentation application layers. Furthermore, we will have a completely independent object to control the presentation layer. The independence between the objects/layers in our project that the MVC provides will make maintenance somewhat easier and code reuse very easy (as you'll see below).

As a general practice we know we want to keep the object dependencies in our projects to a minimum so changes are easy and we can reuse the code we've worked so hard on. To accomplish this we will follow a general principle of "programming to the interface, not the class" using the MVC pattern.

Our mission, if we choose to accept it...

We have been commissioned to build a ACME 2000 Sports Car business object and our task is to create a simple windows interface to (1) display the vehicle's current direction and speed, and (2) enable the end user to change direction, accelerate, and decelerate.  And of course, there will be scope creep. 

There are already rumors at ACME that if our project is successful, we will eventually a need to develop a similar interface for the ACME 2 Pickup Truck and the ACME 1 Tricycle. As developers, we also know that the ACME management team will eventually say "Hey, this is really cool. Can we see it on the company's intranet?" All of this in mind, we want to deliver a product that will be easily scalable so we can be sure to have food on our plates for some time.

So, coincidentally, we think... "This is a perfect situation to use the MVC!!".

Our Architecture Overview

Ok, now we know that we want to use the MVC, we need to figure out what the heck it is. Through our research we come up with the three parts of the MVC: The Model, Control, and View. In our system, the Model would be our car, the View would be the user interface, and the Control is what ties the two together.

Model-View-Control Overview

 
To make any changes to the Model (our ACME 2000 sports car), we'll be using our Control. Our Control will make the request to the Model (our ACME 2000 sports car), and update our View, which is our user interface (UI).

This seems simple enough, but here's the first problem we have to solve: What happens when the end user wants to make a change to our ACME 2000 sports car, such as going faster or turning? They are going to have to do it by requesting a change using the Control, through the View (our windows form).

Model-View-Control Model
 
Now we are left with one last problem to solve. What if the View doesn't have the necessary information to display the current state of the Model?  We're going to have to add one more arrow to our diagram: The View will be able to request the Model's state in order to get what it needs to display the information about the state of the Model.

Model View Control View

Finally, our end user (our driver) will be interacting with our entire ACME Vehicle Control system through the View.  If they want to request a change to the system, such as adding a bit of acceleration, the request will be initiated from the View and handled by the Control.  

The Control will then ask the Model to change and make any necessary changes to the View. For example if the ACME 2000 Sports Car has a "floor it" request from an unruly driver and is now traveling to fast to make a turn, the Control will know to disable the ability to turn in the View, thus preventing a catastrophic pileup in the middle of rush-hour (whew!).

The Model (the ACME 2000 Sports Car) will notify the View that it's speed has increased and the View will update where appropriate.

So after all that, here's the overview of what we will be building:

Model View Control View

Getting Started: Parts... Parts... Parts...

Being developers who always think ahead, we want to be sure our system will have a long and prosperous life. This means being prepared for as many changes at ACME as possible. In order to do this we know to follow two golden rules... "keep your classes loosely coupled" and, in order to accomplish this... "program to the interface".

So we will make three interfaces (as you may have guessed, one for the Model, one for the View, and one for the Control).

After much research and laborious interviews with the folks at ACME, we find out more about the system specifications. We want to be sure that we can set the maximum speeds for traveling forward, backwards, and turning. We also need to be able to speed up, slow down, and turn left and right. Our "dashboard" view must display the current speed and direction.

It's a tall order to implement all of these requirements, but we're sure we can handle it...

First, let's take care of some preliminary items.  We'll need something to represent the direction and turn requests.  We'll create two enumerables, AbsoluteDirection and RelativeDirection.

  1. public enum AbsoluteDirection {  
  2.  North = 0, East, South, West  
  3. }  
  4. public enum RelativeDirection {  
  5.  Right,  
  6.  Left,  
  7.  Back  
  8. }  
Next, let's tackle the Control interface. We know the Control has to pass requests to the Model, specifically: Accelerate, Decelerate, and Turn. We'll create an IVehicleControl interface with the appropriate methods.
  1. public interface IVehicleControl  
  2. {  
  3.     void Accelerate(int paramAmount);  
  4.     void Decelerate(int paramAmount);  
  5.     void Turn(RelativeDirection paramDirection);  
  6. }  
Now we'll put together the Model interface.  We need to know the Vehicle's name, speed, maximum speed, maximum reverse speed, maximum turn speed and direction. We also need methods to accelerate, decelerate, and turn.
  1. public interface IVehicleModel  
  2. {  
  3.     string Name { getset; }  
  4.     int Speed { getset; }  
  5.     int MaxSpeed { get; }  
  6.     int MaxTurnSpeed { get; }  
  7.     int MaxReverseSpeed { get; }  
  8.     AbsoluteDirection Direction { getset; }  
  9.     void Turn(RelativeDirection paramDirection);  
  10.     void Accelerate(int paramAmount);  
  11.     void Decelerate(int paramAmount);  
  12. }  
And Finally, we'll put together the View interface. We know the view should expose some functionality to the Control, such as enabling and disabling acceleration, deceleration, and turn requests.
  1. public class IVehicleView  
  2. {  
  3.     void DisableAcceleration();  
  4.     void EnableAcceleration();  
  5.     void DisableDeceleration();  
  6.     void EnableDeceleration();  
  7.     void DisableTurning();  
  8.     void EnableTurning();  
  9. }  
Now we have to make a few tweaks to our interfaces to allow them to interact. First of all, any Control should be aware of it's View and Model, so we'll add "SetModel" and "SetView" methods to our IvehicleControl interface:
  1. public interface IVehicleControl  
  2. {  
  3.     void RequestAccelerate(int paramAmount);  
  4.     void RequestDecelerate(int paramAmount);  
  5.     void RequestTurn(RelativeDirection paramDirection);  
  6.     void SetModel(IVehicleModel paramAuto);  
  7.     void SetView(IVehicleView paramView);  
  8. }  
The next part is a bit tricky. We want the View to be aware of changes in the Model. To do this we'll use a GOF design pattern "Observer".

To implement the Observer pattern, we need to add the following methods to the Model (which will be "observed" by the View): AddObserver, RemoveObserver, and NotifyObservers.

  1. public interface IVehicleModel  
  2. {  
  3.     string Name { getset; }  
  4.     int Speed { getset; }  
  5.     int MaxSpeed { get; }  
  6.     int MaxTurnSpeed { get; }  
  7.     int MaxReverseSpeed { get; }  
  8.     AbsoluteDirection Direction { getset; }  
  9.     void Turn(RelativeDirection paramDirection);  
  10.     void Accelerate(int paramAmount);  
  11.     void Decelerate(int paramAmount);  
  12.     void AddObserver(IVehicleView paramView);  
  13.     void RemoveObserver(IVehicleView paramView);  
  14.     void NotifyObservers();  
  15. }  
...and add the following method to the View (which will be "observing" the Model). What will happen is the Model will have a reference to the View. When the Model changes, it will call the NotifyObservers() method and pass a reference to itself and notify the View of a change by calling the Update() method of the View. (It will become clear as mud when we wire everything up later).
  1. public class IVehicleView  
  2. {  
  3.     void DisableAcceleration();  
  4.     void EnableAcceleration();  
  5.     void DisableDeceleration();  
  6.     void EnableDeceleration();  
  7.     void DisableTurning();  
  8.     void EnableTurning();  
  9.     void Update(IVehicleModel paramModel);  
  10. }  
So now we have our interfaces put together. We are only going to use references to these interfaces in the rest of our code to ensure we have loose coupling (which we know is a good thing). Any user interface that shows the state of a Vehicle will implement IVehicleView, all of our ACME automobiles will implement IVehicleModel, and we'll make controls for our ACME automobiles with ACME vehicle controls which will implement IVehicleControl.

Next... What things will have things in common?

We know all our vehicles should act the same, so we're going to create a common code base "skeleton" to handle their operation. This is going to be an abstract class because we don't want anyone driving around a skeleton (you can't make an instance of an abstract class). We'll call it Automobile. We'll use an ArrayList (from System.Collections) to keep track of all the interested Views (remember the Observer pattern?). We could have used a plain old array of IVehicleView references, but we're all getting fatigued at this point and want to get through this article. If you're interested, check out the implementation of the AddObserver, RemoveObserver, and NotifyObservers methods to get an idea of how the Observer pattern works by helping our IVehicleModel interact with the IVehicleView. Every time there is a change in speed or direction, the Automobile notifies all IVehicleViews

  1. public abstract class Automobile : IVehicleModel  
  2. {  
  3.     #region "Declarations "  
  4.     private ArrayList aList = new ArrayList();  
  5.     private int mintSpeed = 0;  
  6.     private int mintMaxSpeed = 0;  
  7.     private int mintMaxTurnSpeed = 0;  
  8.     private int mintMaxReverseSpeed = 0;  
  9.     private AbsoluteDirection mDirection = AbsoluteDirection.North;  
  10.     private string mstrName = "";  
  11.     #endregion  
  12.     #region "Constructor"  
  13.     public Automobile(int paramMaxSpeed, int paramMaxTurnSpeed, int paramMaxReverseSpeed, string paramName)  
  14.     {  
  15.         this.mintMaxSpeed = paramMaxSpeed;  
  16.         this.mintMaxTurnSpeed = paramMaxTurnSpeed;  
  17.         this.mintMaxReverseSpeed = paramMaxReverseSpeed;  
  18.         this.mstrName = paramName;  
  19.     }  
  20.     #endregion  
  21.     #region "IVehicleModel Members"  
  22.     public void AddObserver(IVehicleView paramView)  
  23.     {  
  24.         aList.Add(paramView);  
  25.     }  
  26.     public void RemoveObserver(IVehicleView paramView)  
  27.     {  
  28.         aList.Remove(paramView);  
  29.     }  
  30.     public void NotifyObservers()  
  31.     {  
  32.         foreach (IVehicleView view in aList)  
  33.         {  
  34.             view.Update(this);  
  35.         }  
  36.     }  
  37.     public string Name  
  38.     {  
  39.         get  
  40.         {  
  41.             return this.mstrName;  
  42.         }  
  43.         set  
  44.         {  
  45.             this.mstrName = value;  
  46.         }  
  47.     }  
  48.     public int Speed  
  49.     {  
  50.         get  
  51.         {  
  52.             return this.mintSpeed;  
  53.         }  
  54.     }  
  55.     public int MaxSpeed  
  56.     {  
  57.         get  
  58.         {  
  59.             return this.mintMaxSpeed;  
  60.         }  
  61.     }  
  62.     public int MaxTurnSpeed  
  63.     {  
  64.         get  
  65.         {  
  66.             return this.mintMaxTurnSpeed;  
  67.         }  
  68.     }  
  69.     public int MaxReverseSpeed  
  70.     {  
  71.         get  
  72.         {  
  73.             return this.mintMaxReverseSpeed;  
  74.         }  
  75.     }  
  76.     public AbsoluteDirection Direction  
  77.     {  
  78.         get  
  79.         {  
  80.             return this.mDirection;  
  81.         }  
  82.     }  
  83.     public void Turn(RelativeDirection paramDirection)  
  84.     {  
  85.         AbsoluteDirection newDirection;  
  86.         switch (paramDirection)  
  87.         {  
  88.             case RelativeDirection.Right:  
  89.                 newDirection = (AbsoluteDirection)((int)(this.mDirection + 1) % 4);  
  90.                 break;  
  91.             case RelativeDirection.Left:  
  92.                 newDirection = (AbsoluteDirection)((int)(this.mDirection + 3) % 4);  
  93.                 break;  
  94.             case RelativeDirection.Back:  
  95.                 newDirection = (AbsoluteDirection)((int)(this.mDirection + 2) % 4);  
  96.                 break;  
  97.             default:  
  98.                 newDirection = AbsoluteDirection.North;  
  99.                 break;  
  100.         }  
  101.         this.mDirection = newDirection;  
  102.         this.NotifyObservers();  
  103.     }  
  104.     public void Accelerate(int paramAmount)  
  105.     {  
  106.         this.mintSpeed += paramAmount;  
  107.         if (mintSpeed >= this.mintMaxSpeed) mintSpeed = mintMaxSpeed;  
  108.         this.NotifyObservers();  
  109.     }  
  110.     public void Decelerate(int paramAmount)  
  111.     {  
  112.         this.mintSpeed -= paramAmount;  
  113.         if (mintSpeed <= this.mintMaxReverseSpeed) mintSpeed = mintMaxReverseSpeed;  
  114.         this.NotifyObservers();  
  115.     }  
  116.     #endregion  
  117. }  
Last but not least...

Now that our "ACME Framework" is in place, we just have to set up our concrete classes and our interface. Let's take care of the last two class first which will be our Control and our Model...

Here's our concrete AutomobileControl which implements the IVehicleControl interface. Our AutomobileControl will also set the View depending on the state of the Model (check out the SetView method which is called every time there is a request passed to the Model).

Notice, we just have references to the IVehicleModel (not the Automobile abstract class) to keep things loose and IVehicleView (not a specific View).

  1. public class AutomobileControl : IVehicleControl  
  2. {  
  3.     private IVehicleModel Model;  
  4.     private IVehicleView View;  
  5.     public AutomobileControl(IVehicleModel paramModel, IVehicleView paramView)  
  6.     {  
  7.         this.Model = paramModel;  
  8.         this.View = paramView;  
  9.     }  
  10.     public AutomobileControl()  
  11.     {  
  12.     }  
  13.     #region IVehicleControl Members  
  14.     public void SetModel(IVehicleModel paramModel)  
  15.     {  
  16.         this.Model = paramModel;  
  17.     }  
  18.     public void SetView(IVehicleView paramView)  
  19.     {  
  20.         this.View = paramView;  
  21.     }  
  22.     public void RequestAccelerate(int paramAmount)  
  23.     {  
  24.         if (Model != null)  
  25.         {  
  26.             Model.Accelerate(paramAmount);  
  27.             if (View != null) SetView();  
  28.         }  
  29.     }  
  30.     public void RequestDecelerate(int paramAmount)  
  31.     {  
  32.         if (Model != null)  
  33.         {  
  34.             Model.Decelerate(paramAmount);  
  35.             if (View != null) SetView();  
  36.         }  
  37.     }  
  38.     public void RequestTurn(RelativeDirection paramDirection)  
  39.     {  
  40.         if (Model != null)  
  41.         {  
  42.             Model.Turn(paramDirection);  
  43.             if (View != null) SetView();  
  44.         }  
  45.     }  
  46.     #endregion  
  47.     public void SetView()  
  48.     {  
  49.         if (Model.Speed >= Model.MaxSpeed)  
  50.         {  
  51.             View.DisableAcceleration();  
  52.             View.EnableDeceleration();  
  53.         }  
  54.         else if (Model.Speed <= Model.MaxReverseSpeed)  
  55.         {  
  56.             View.DisableDeceleration();  
  57.             View.EnableAcceleration();  
  58.         }  
  59.         else  
  60.         {  
  61.             View.EnableAcceleration();  
  62.             View.EnableDeceleration();  
  63.         }  
  64.         if (Model.Speed >= Model.MaxTurnSpeed)  
  65.         {  
  66.             View.DisableTurning();  
  67.         }  
  68.         else  
  69.         {  
  70.             View.EnableTurning();  
  71.         }  
  72.     }  
  73. }  
Here's our ACME200SportsCar class (which extends the Automobile abstract class which implements the IVehicleModel interface):
  1. public class ACME2000SportsCar : Automobile  
  2. {  
  3.     public ACME2000SportsCar(string paramName) : base(250, 40, -20, paramName) { }  
  4.     public ACME2000SportsCar(string paramName, int paramMaxSpeed, int paramMaxTurnSpeed, int paramMaxReverseSpeed) :  
  5.     base(paramMaxSpeed, paramMaxTurnSpeed, paramMaxReverseSpeed, paramName)  
  6.     { }  
  7. }  
And now for our View...

Now we have to create the last of our three ACME MVC components... the View

We'll create a AutoView user control and have it implement the IVehicleView interface. The AutoView component will have references to our control and model interfaces:

  1. public class AutoView : System.Windows.Forms.UserControl, IVehicleView  
  2. {  
  3.     private IVehicleControl Control = new ACME.AutomobileControl();  
  4.     private IVehicleModel Model = new ACME.ACME2000SportsCar("Speedy");  
  5. }  
We also need to wire everything up in the constructor for the UserControl.
  1. public AutoView()  
  2. {  
  3.     // This call is required by the Windows.Forms Form Designer.  
  4.     InitializeComponent();  
  5.     WireUp(Control, Model);  
  6. }  
  7. public void WireUp(IVehicleControl paramControl, IVehicleModel paramModel)  
  8. {  
  9.     // If we're switching Models, don't keep watching  
  10.     // the old one!   
  11.     if (Model != null)  
  12.     {  
  13.         Model.RemoveObserver(this);  
  14.     }  
  15.     Model = paramModel;  
  16.     Control = paramControl;  
  17.     Control.SetModel(Model);  
  18.     Control.SetView(this);  
  19.     Model.AddObserver(this);  
  20. }  
Next, we'll add our buttons, a label to display the status of the ACME2000 Sports Car and a status bar just for kicks and fill out the code for all the buttons. 

Model View Control Buttons

  1. private void btnAccelerate_Click(object sender, System.EventArgs e)  
  2. {  
  3.     Control.RequestAccelerate(int.Parse(this.txtAmount.Text));  
  4. }  
  5. private void btnDecelerate_Click(object sender, System.EventArgs e)  
  6. {  
  7.     Control.RequestDecelerate(int.Parse(this.txtAmount.Text));  
  8. }  
  9. private void btnLeft_Click(object sender, System.EventArgs e)  
  10. {  
  11.     Control.RequestTurn(RelativeDirection.Left);  
  12. }  
  13. private void btnRight_Click(object sender, System.EventArgs e)  
  14. {  
  15.     Control.RequestTurn(RelativeDirection.Right);  
  16. }  
Add a method to update the interface...

  1. public void UpdateInterface(IVehicleModel auto)  
  2. {  
  3.     this.label1.Text = auto.Name + " heading " + auto.Direction.ToString() + " at speed: " + auto.Speed.ToString();  
  4.     this.pBar.Value = (auto.Speed > 0) ? auto.Speed * 100 / auto.MaxSpeed : auto.Speed * 100 / auto.MaxReverseSpeed;  
  5. }  
Finally, we'll wire up the IVehicleView interface methods...

 

  1. public void DisableAcceleration()  
  2. {  
  3.     this.btnAccelerate.Enabled = false;  
  4. }  
  5. public void EnableAcceleration()  
  6. {  
  7.     this.btnAccelerate.Enabled = true;  
  8. }  
  9. public void DisableDeceleration()  
  10. {  
  11.     this.btnDecelerate.Enabled = false;  
  12. }  
  13. public void EnableDeceleration()  
  14. {  
  15.     this.btnDecelerate.Enabled = true;  
  16. }  
  17. public void DisableTurning()  
  18. {  
  19.     this.btnRight.Enabled = this.btnLeft.Enabled = false;  
  20. }  
  21. public void EnableTurning()  
  22. {  
  23.     this.btnRight.Enabled = this.btnLeft.Enabled = true;  
  24. }  
  25. public void Update(IVehicleModel paramModel)  
  26. {  
  27.     this.UpdateInterface(paramModel);  
  28. }  
And we're off!!!

Now we can go for a test drive in the ACME2000 Sports Car. Everything is going as planned and then we run into an ACME executive who wants to drive a pickup truck instead of a sports car. 

Good thing we used the MVC! All we need to do is create a new ACMETruck class, wire it up, and we're in business!

  1. public class ACME2000Truck : Automobile  
  2. {  
  3.     public ACME2000Truck(string paramName) : base(80, 25, -12, paramName) { }  
  4.     public ACME2000Truck(string paramName, int paramMaxSpeed, int paramMaxTurnSpeed, int paramMaxReverseSpeed) :  
  5.     base(paramMaxSpeed, paramMaxTurnSpeed, paramMaxReverseSpeed, paramName)  
  6.     { }  
  7. }  
in the AutoView, we just have to build the truck and wire it up!
  1. private void btnBuildNew_Click(object sender, System.EventArgs e)  
  2. {  
  3.     this.autoView1.WireUp(new ACME.AutomobileControl(), new ACME.ACME2000Truck(this.txtName.Text));  
  4. }  
If we wanted a new Control that only allowed us to increase or decrease the speed by a maximum of 5mph, it's a snap!  Create a SlowPokeControl (same as our AutoControl, but with limits on how much a Model will be requested to accelerate)
  1. public void RequestAccelerate(int paramAmount)  
  2. {  
  3.     if (Model != null)  
  4.     {  
  5.         int amount = paramAmount;  
  6.         if (amount > 5) amount = 5;  
  7.         Model.Accelerate(amount);  
  8.         if (View != null) SetView();  
  9.     }  
  10. }  
  11. public void RequestDecelerate(int paramAmount)  
  12. {  
  13.     if (Model != null)  
  14.     {  
  15.         int amount = paramAmount;  
  16.         if (amount > 5) amount = 5;  
  17.         Model.Accelerate(amount);  
  18.         Model.Decelerate(amount);  
  19.         if (View != null) SetView();  
  20.     }  
  21. }  
If we want to make our ACME2000 Truck a SlowPoke, we just wire it up in the AutoView!
  1. private void btnBuildNew_Click(object sender, System.EventArgs e)  
  2. {  
  3.     this.autoView1.WireUp(new ACME.SlowPokeControl(), new ACME.ACME2000Truck(this.txtName.Text));  
  4. }  
And finally, if we wanted a web-enabled interface, all we have to do is create a web project and on the UserControl implement the IVehicleView interface! 

In Conclusion...

As you can see, using the MVC to help build code to control interfaces that is very loosely coupled makes life much easier when it comes to change requests. It also makes the impact of changes negligible and you can reuse your interfaces and abstract classes almost anywhere. There are a couple of places where we can build some more flexibility in our project, especially in terms of requesting changes to our Model's state, but that will have to wait for next time.

In the meanwhile, keep the MVC in mind for your next project... You won't regret it.

Happy Driving.


Similar Articles