How to apply the MVC pattern to GUI development


Question

I am primary a web developer but I do have a very good understanding of C++ and C#. However, recently I have writing a GUI application and I have started to get lost in how to handle the relationship between my controller and view logic. In PHP it was very easy - and I could write my own MVC pattern with my eyes closed - mainly because of how PHP is stateless and you regenerate the entire form per request. But in application programming languages I get lost very quickly.

My question is: how would I separate my controller from view? Should the view attach to events from the controller - or should the view implement an interface that the controller interacts with?

1
8
10/7/2008 7:11:43 AM

Accepted Answer

If I was you I would expose events from an interface of your view. This would allow you to make the controller central to the entire interaction.

The controller would load first and instantiate the view, I would use dependency injection so that you don't create a dependency on the view itself but only on the interface. The controller would access the model and load data into the view. The controller would bind to events defined on the view interface. The controller would then handle saving of data back to the model via an event.

If you wanted to you could also use an event broker which would void the need to declare an interface per view. This way you could bind to events through attributes.

This would leave you with the Controller being dependent on the model and the view interface, the view being dependent on the data only and the model having no dependencies.

Some examples of the above design thinking can be found in CAB and the Smart Client Software Factory Link To Smart Client. They use the MVP pattern but it could equally easily be applied to the MVC pattern.

6
10/30/2008 12:59:11 AM

Most every GUI framework (from MFC to SWT to whatever) is already MVC based. In fact, the MVC pattern was first created by Smalltalk-80 and later first really used for GUI development.

Double check and look at the standards and suggested practices for your GUI toolkit of choice. Sometimes MVC won't be a good pattern to work with when solving a certain problem or working with a particular toolkit.

Remember: MVC is a great pattern but isn't a one size fits all solution, don't try and force a problem into MVC when event-based or functional style programming will make your life easier.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon