Model-View-Controller Example Code
adapted from an example by David Matuszek
This is a simple example of Model-View-Controller, with special emphasis
on the Observer /Observable technique (highlighted
in blue). All it does is put up a black circle that gradually turns red,
then the program quits.
The Model does the work. Whenever it does something that another class
might be interested in, it "broadcasts" the fact to all other
classes that might be interested. Note that the Model does not need
to know or care anything about which other classes, if any, might
be interested, so it remains completely independent of those classes.
Model.java |
import java.awt.*;
import java.util.*;
public class Model extends Observable {
public Color color = new Color(0x010000);
private int count = 10;
void doSomething() {
if (--count <= 0) {
color = color.brighter();
count = 10;
//
setChanged();
notifyObservers();
}
}
}
|
The View is interested in observing the Model class; it does this by
implementing a version of the update method, which will automatically
be called any time a class that it is observing broadcasts something.
View.java |
import java.awt.*;
import java.util.*;
public class View extends Canvas implements Observer {
Color color;
public void paint(Graphics g) {
if (color == null) return;
g.setColor(color);
g.fillOval(0, 0, getWidth(), getHeight());
}
public void update(Observable observable, Object arg) {
color = ((Model)observable).color;
repaint();
}
}
|
The Controller in this program doesn't actually have any controls. However,
it does set up the GUI, create the Model and the View, and register
the View as an observer of the Model.
Controller.java |
import java.awt.*;
public class Controller extends Frame {
static Model model = new Model();
static View view = new View();
public static void main(String args[]) {
Frame f = new Frame();
f.add(view);
f.setSize(200, 220);
f.setVisible(true);
model.addObserver(view);
for (int i = 0; i < 200; i++) {
model.doSomething();
try { Thread.sleep(20); } catch (InterruptedException e) {}
}
f.dispose();
}
}
|
This code is available as an executable jar file
and also as a BlueJ project as a zip file.
|