I am looking into the MVC from a Command line point of view (not web and no framework).. nice and simple. the only thing that confuses me is the View part of this? (well it may
define an abstract yet simple MVC program as:
interface Model {
public void setName(String name);
}
interface View {
public String prompt(String prompt);
}
class Controller {
private final Model model;
private final View view;
public Controller(Model model, View view) {
this.model = model;
this.view = view;
}
public void run() {
String name;
while ((name = view.prompt("\nmvc demo> ")) != null) {
model.setName(name);
}
}
}
then use the Observer pattern (built-in since JDK 1.0, see here) in order to fill the concrete classes:
class Person extends Observable implements Model {
private String name;
public Person() {
}
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
setChanged();
notifyObservers(newName);
}
}
class TUI implements Observer, View { // textual UI
private final BufferedReader br;
public TUI(Reader reader) {
this.br = new BufferedReader(reader);
}
public void update(Observable o, Object arg) {
System.out.println("\n => person updated to " + arg);
}
public String prompt(String prompt) {
try {
System.out.print(prompt);
return br.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
The main class, that is only responsible to build and connect together the components:
TUI view = new TUI(new StringReader("David\nDamian\nBob\n"));
Person model = new Person();
model.addObserver(view);
Controller controller = new Controller(model, view);
controller.run();
the ouput of this program is:
mvc demo> => person updated to David mvc demo> => person updated to Damian ...