Architectural Manifesto: The MVC Design Pattern in MIDP Development

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Architectural manifesto: The MVC design pattern in MIDP development http://www-128.ibm.

com/developerworks/wireless/library/wi-arch6/

Architectural manifesto: The MVC design pattern in


MIDP development
Simplify your GUI development process with MVC

Level: Introductory
Mikko Kontio (mikko.kontio@enfo.fi), Technology manager, Enfo Solutions
09 Sep 2004

Learn how to use the Model-View-Controller pattern in your MIDP user interface development. Start
with an overview of the structure of the MVC pattern, then see how it can be applied in a real-life case.

Introduction
In everyday software development you often encounter the same problems again and again. Rather than solve the
same problem each time, it makes sense to document the solution and re-use it. Design patterns are essentially
documented, generalized solutions to common problems in application development.
It has been said that there are two phases to implementing a design pattern: understanding it, and then using it. In
this article, you'll be introduced to the Model-View-Controller (MVC) pattern and learn how to make it part of
your MIDP user interface development. You'll start with an overview of the MVC pattern structure, then see how it
can be applied in a real-life case.

What is MVC?
Some people categorize MVC as an architectural style, while others (such as myself) think of it as a design pattern.
Whereas architectural styles tend to dictate the structure of the whole application, design patterns focus on solving
one or two particular problems. The MVC pattern solves the problem of updating an application's views (UI
screens) as its data changes.
The MVC pattern consists of three parts: model, view, and controller. The model represents the data and business
logic of the application. In an accounting application, the model would be the part of the application responsible
for fetching data from the lower layers or components, handling the data, making any necessary calculations, and
notifying all the views registered to that particular data of any changes.
The view is the actual screen that displays data and related commands to the user. Some applications offer multiple
views of a given model, or even of the same data. Many of the popular spreadsheet applications present different
kinds of charts representing a single block of data.
The controller receives user actions and dispatches them to the model. You can assign a single class to be the
controller or divide the controller's responsibilities among several classes.
Figure 1 is a simple diagram of the MVC pattern. The view contains the graphical user interface, which is the part
of the application the user can see. When the user alters the data on the screen and then initiates an action, that
action goes to the controller. The controller determines what kind of action has been requested and calls the
appropriate interfaces of the model. The model can consist of several components, classes, or packages, depending
on the technology that implement the application's business logic.

Figure 1. Elements of the MVC design pattern

Стр. 1 из 5 04.03.2008 10:11


Architectural manifesto: The MVC design pattern in MIDP development http://www-128.ibm.com/developerworks/wireless/library/wi-arch6/

Notice that the view has registered itself to the model. The model notifies the view of data changes in its various
components. This way, the view doesn't have to poll the model about changes in the application data.

Using MVC with MIDP


Now, you'll build an example application so you can see how the MVC design pattern works in an MIDP user
interface development. There are essentially two ways to build an MIDP 2.0 interface: you can use the Form class,
which gives you a basic UI template consisting of predefined forms; or you can use the Canvas class and create
everything from scratch. For the purpose of this article, you'll work with the Form class.
This simple Form-based application displays a screen with a value that is constantly updated. In real life, the
model might need to reflect all the functions associated with a huge data model and the business logic necessary to
handle it. In this case, however, you're working with a simple, easily changed value, and no server back end, so the
model is actually just a simulator of a real-life data model. The simulator changes the value (an integer) inside the
model as other users or other applications would do with the real-life data model.
You can see a screen capture of the example application in Figure 2. The user has just updated the value of the
model to 40, whereupon the simulator has increased it a few times.

Figure 2. A screen capture of the application

The example application


The example application consists of three classes: MVCMIDlet, Model, and View, which extends the MIDP
Form class. As you can see in Figure 3, the MVCMIDlet class acts as the controller and the others are named
according to their roles. The application structure is quite simple.

Стр. 2 из 5 04.03.2008 10:11


Architectural manifesto: The MVC design pattern in MIDP development http://www-128.ibm.com/developerworks/wireless/library/wi-arch6/

Figure 3. A class diagram of the example application

From this point, you'll concentrate on the code, which should amply demonstrate the three components of the MVC
pattern, as well as their use in building an MIDP interface.
The controller

The MVCMIDlet class shown in Listing 1 is a typical MIDlet class. It has all the mandatory methods, and it also
implements the CommandListener interface. Every time the user updates the value of the TextField the
controller updates the model. The MIDlet class controls all of the commands and the setting of the command
listener.

Listing 1. MVCMIDlet is the controller


package com.kontio;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import java.io.*;

public class MVCMIDlet extends MIDlet implements CommandListener {

private Display display;


private Command exitCommand = new Command("Exit", Command.EXIT, 60);
private Command updateCommand = new Command("Update", Command.ITEM, 60);

private Model model = new Model();


private View v = null;

public MVCMIDlet() {
v = new View(model);
model.start();
display = Display.getDisplay(this);

v.addCommand(exitCommand);
v.addCommand(updateCommand);
v.setCommandListener(this);

display.setCurrent(v);
}

public void startApp() {


}

public void pauseApp() {


}

public void destroyApp(boolean unconditional) {


display.setCurrent((Displayable)null);
}

public void commandAction(Command c, Displayable s) {


if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
if (c == updateCommand) {
int i = Integer.parseInt(v.getValue());
model.setCount(i);
}
}
}

The model

The Model class simulates an actual model that would be used by multiple users. As users change the state of the
model (by changing its values), the model notifies its registered views. The run() method is the heart of the
simulator; as you can see, it simply increases the value of the count every 50 milliseconds.

Listing 2. The Model class simulates an actual model

Стр. 3 из 5 04.03.2008 10:11


Architectural manifesto: The MVC design pattern in MIDP development http://www-128.ibm.com/developerworks/wireless/library/wi-arch6/

package com.kontio;
import java.util.*;

public class Model implements Runnable{


Vector reg = new Vector(5);
int count = 0;
boolean play = false;
Thread thread = null;

public Model(){
}

public synchronized void start() {


play=true;
thread = new Thread(this);
thread.start();
}

public void register(View v){


reg.addElement(v);
}

public void stop(){


play=false;
}

public void run(){


while (play){
count++;
informViews();
try {
thread.sleep(50);
} catch (java.lang.InterruptedException e){}
}
}

private void informViews(){


for (Enumeration e = reg.elements() ; e.hasMoreElements() ;) {
View v = (View)e.nextElement();
v.update();
}
}

public String getCount(){


return ""+count;
}

public void setCount(int count){


this.count = count;
}

The view

The View class is inherited from the MIDP 2.0 Form class. It has one TextField and one StringItem. The
StringItem shows the value of the model and the TextField offers a field to update the value. Naturally, this
isn't the only way to implement MVC, but it is one possibility.

Listing 3. The View class is inherited from Form


package com.kontio;
import javax.microedition.lcdui.*;

public class View extends Form{


private StringItem si = new StringItem("Count","");
private TextField tf = new TextField("Count", null, 5, TextField.NUMERIC);

private Model model = null;

public View(Model model){


super("Count");
this.model = model;
this.model.register(this);
this.append(si);
this.append(tf);
update();
}

public void update(){


si.setText(model.getCount());
}

public String getValue(){


return tf.getString();
}
}

Стр. 4 из 5 04.03.2008 10:11


Architectural manifesto: The MVC design pattern in MIDP development http://www-128.ibm.com/developerworks/wireless/library/wi-arch6/

In conclusion
Design patterns let you effectively and efficiently solve common problems in application development. The MVC
design pattern is a proven solution for applications where the user interface needs to show up-to-date information
and polling the server isn't an option.
In MVC, the user interface (called the view) registers itself as a listener to certain parts of the application's
underlying business and functional logic, as represented by the model. The model then notifies all registered views
whenever there is a change in the data. Completing the cycle, the controller receives user actions and dispatches
them to the model.
In this month's column I've introduced you to the structure of MVC and walked you through an implementation of
MVC in an MIDP environment. While very simple, the example application demonstrates the three components of
the Model-View-Controller pattern and shows how they can work together as the underlying framework of an
MIDP interface.

Resources
Learn more about MIDP development with Mikko's Designing MIDP applications (developerWorks,
February 2004).

This column demonstrates the simplicity of the Form class, but MIDP 2.0 offers far more advanced features
for user interface development. Mikko's Custom GUI development with MIDP 2.0 (developerWorks, May
2003) shows you how to build custom GUI elements with the extendable CustomItem class.

For a more in-depth introduction to MIDP development, delve into John Muchow's J2ME 101 series
(developerWorks, November 2003), a comprehensive four-part introduction to Java 2 Platform, Micro
Edition (J2ME) and the Mobile Information Device Profile.

David Gallardo's Design Patterns 101 (developerWorks, January 2002) tutorial introduces the theory and
practice of pattern-based development.

IBM's Thin Client Framework (TCF) is a lightweight programming framework for Java client applications. In
the two-part Introduction to Thin Client Framework (developerWorks, January 2003), developers Barry
Feigenbaum and Peter Bahrs show you how TCF raises the Model-View-Controller design pattern to the level
of an application architecture.

Visit the Sun Microsystems developer network to learn more about MIDP 2.0 and J2ME.

Don't miss a single installment of Mikko's Architectural manifesto column. See the column series page for a
complete listing of previous installments in this series.

See the developerWorks Wireless technology zone for a continuously updated collection of articles and
tutorials on mobile application design and development.

About the author

Mikko Kontio works as a production manager for the leading-edge Finnish software company, Softera. He holds a
master's degree in computer science and is the author and co-author of several books, the latest being Professional
Mobile Java with J2ME, published by IT Press. Mikko can be reached at mikko.kontio@softera.fi.

Стр. 5 из 5 04.03.2008 10:11

You might also like