Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.ArrayList;
// HelloMVC: a simple MVC example
// the model is just a counter
// inspired by code by Joseph Mack, http://www.austintek.com/mvc/
// View interface
interface IView {
public void updateView();
}
public class Model {
// the data in the model, just a counter
private int counter;
// all views of this model
private ArrayList<IView> views = new ArrayList<IView>();
// set the view observer
public void addView(IView view) {
views.add(view);
view.updateView();
}
public int getCounterValue() {
return counter;
}
public void incrementCounter() {
if (counter < 5) {
counter++;
System.out.println("Model: increment counter to " + counter);
notifyObservers();
}
}
// notify the IView observer
private void notifyObservers() {
for (IView view : this.views) {
System.out.println("Model: notify View");
view.updateView();
}
}
}