The aim of this tutorial is to introduce the use of a coding style called Model View Controller. You may well have heard of this already, but probably haven’t seen how to put it into practice.
I’m going to use Java to demonstrate it as it is a very commonly used Object Oriented programming language that uses a similar syntax to many other languages.

What is it?

Basically, it’s all about splitting up the components of a program into manageable and efficient chunks. It splits the program up into the following bits:

Model – The key manipulation of the data behind the application.
View – How the data is presented to the user.
Controller – Control of events in the application.

The key part of this is that the View is separated from everything else. That means that to change the appearance of an application you only have to plug in a new view and leave the application logic alone.

How do I do it?

Ok, so that’s the basic theory taken care of. There are many more resources online about what it is, but here’s an example of how you do it. Don’t worry if you’re confused before we’ve even got to the examples; this is just a quick intro and it will all become clear when you see it in action.
For the example, I’m going to make a small application that multiplies 2 random numbers together every 5 seconds and shows the result.

The logic is very simple. If something changes in the Model, it notifies the View and Controller. Each of these two listens out for notifications from the Model and updates accordingly when it receives one.
In Java, this communication is dealt with using the Observer and Observable classes from the Java API. The Model extends Observable (so that the other classes can look out for its updates) and the View and Controller implement Observer (so that they can be capable of looking out for updates).

What this does is just let the Observers know that the Model has changed, then sends an object to them for them to listen to. In this simple program this will be the actual number that is to be shown, however in bigger programs it is sometimes better to simply send a marker telling the View what needs to be updated and the View can then get it from the Model on demand.

For all of the code, have a look at the source code at the bottom. Here’s a quick summary of the important bits.

Model:
The Model is pretty simple, but the important bit is that it has no distinct mention of either the View or the Controller. It lives in its own little bubble and simply broadcasts the updates.
When the Model needs to update, it uses the following piece of code:

this.setChanged();
this.notifyObservers(Object o);

Note here that Object o can be anything that extends Object, such as 23 (an int) or “bob” (a String).

View and Controller:
The View and Controller registers itself with the Model using this piece of code:

model.addObserver(this);

This means they are now listening out for any updates from the Model, a bit like a TV aerial listens out for the signal from a TV Mast. They will now pick up every update from the Model, regardless of what the update is.
So, we’re listening so somehow we need a way to hear. This is what the update method is for:

public void update(Observable arg0, Object arg1)
{}

In a big program where the View is watching more than one bit of the Model it may be necessary to figure out which Observable object (arg0) has sent the update, but in this example we know where it’s from so we will ignore arg0. The bit that carries the data is Object arg1, so we make sure it’s not null and then try and extract the data from it. That’s it. Nothing more. There’s no magic, no fancy API’s to be used, no complex data structures to remember and learn.

This is the method that is triggered when the Model sends out an update. Anything that should be done with the data is done in there!
Note that the View needs an instance of the Model and the Controller in it, whereas the Controller only needs an instance of Model.

That’s it; that’s the code.

But why should I use it?

The problem you might have at the moment is that you can’t really see the value of it all. I mean, you could do all of that in one class and it wouldn’t be very messy or difficult at all. Why have 3 classes and use silly Observers and Observables when you could just have one class?

In a word, flexibility. You can change the Views so easily without having to change the back-end implementation. You can even have two different Views for the same Model. This flexibility can be seen in the source code where I have made ViewCommandLine and ViewGUI. When you run the program (using Driver.java) you will be asked which you want to use, and the relevant one will be loaded and used. The Model is the same regardless and no code is duplicated for the back end of things.

Do you see the significance of that? If you don’t, run the source code at the bottom of the page to see how it works.

…got it now? Good!

In order to get that kind of flexibility by coding it all together you would have to always duplicate the Model and Controller sections.

It’s not just flexibility that this adds either, its simplicity and what I suppose you could call abstraction; the Model has no idea what methods the View or Controller need to use, it just sends the data and leaves the rest to the relevant class. This means one View could do hugely complex things with the data and another View could do absolutely nothing with it and both would work fine with the same Model.

Conclusion

So, I hope now that you can kind of see the benefits of the MVC architecture. The best example I’ve ever used it for is making a pinball-style game where the position of the ball updated then sent the data out for the View to pick up. It picked it up and did various weird and wonderful things with it before showing it on the screen. It really was so much simpler to maintain and understand, as well as write.
Remember that in so many instances the only thing that is changed in a program update is the way it looks. Making it simple to do that in the initial coding style means your life will be so much easier in the long run.

Have a look at the source code for a fully commented version and run it to see just how simple it is to show the same data in completely different ways. You will often find that other examples will not register or use the Controller element as an Observer if it doesn’t need to update, but it works either way and I’ve registered it just to show you how.

This is my first tutorial and I hope you’ve understood it and found it useful – please leave a comment to let me know how it could be improved and any other suggestions.

Download the Source Code

Related Posts

More?

If you enjoyed this post, please consider promoting it.
  • Digg
  • del.icio.us
  • StumbleUpon
  • Design Float
  • Reddit
  • Mixx
  • Technorati

Remeber to subscribe to the feed and get future articles delivered to your feed reader.

If you want to discuss this tutorial or any other thoughts you have then you can do so over on our fourm.

Comments

  1. Two suggestions, or questions, or something.

    One: I noticed you have 2 different Views, which like you said is the strength of MVC. But I noticed you don’t have a “View” class. To make it more modular, you’d be better off creating a View class, and handling all the relationship logic that a View has with the Controller. Then with GUIView and CommandLineView, extend View. Now, if you ever need to change the relationship or add functionality to Views, you just have the super class to alter.

    Two: From my classes and my work experience, I don’t understand why the View has an instance of the Model. My understanding of MVC is that Controller is what links Models and Views together. They should be ignorant of each other. That way, moving a model into a new application, or a view, doesn’t require any change. The controller determines what data from the model to use, and then gives data to the view, and the view just simply outputs, not having a care in the world what it says.

  2. Comment by jamie on September 10, 2008 3:16 pm

    @Sean McArthur:
    You’re right with your first point in that if you are going to implement alternative views concurrently then you should have an overall superclass - the reason I don’t here is to show that you can easily switch views and I felt that was best shown by having two totally separate classes.

    The second point is up for debate really and I think depends on how it is taught/implemented - neither way is particularly wrong and as MVC has been around since ~1979 there are a few variants. The approach that I use is that the Controller notifies the Model of a change (e.g. a Keystroke or an ActionEvent like the tick of a timer) -> the Model broadcasts the change to the Observers (including the View) -> and the View is built using data gathered from the Model (i.e. the View gets its data from the Model.
    This approach is widely accepted as the Architectural use of the MVC pattern (or at least, it is on wikipedia and anywhere else I’ve seen it!).
    It really just depends on what you feel comfortable coding with and what fits the application best!

Leave a Comment

(required)

(required)