Separate the user interface (View) from business logic (Model) and the coordination between them (Controller).
// ─── EXAMPLE 1 ──────────────────────────────────────────────────────────────
// WHAT WE ARE IMPLEMENTING:
// A student details manager separating database tables from HTML UI widgets.
//
// WHERE THE MVC FITS IN:
// StudentModel is the Model. StudentView represents the View.
// StudentController acts as the Controller coordinating data updates and UI
// rerenders.
// ────────────────────────────────────────────────────────────────────────────
// --- Model ---
class TaskModel {
private String title;
private boolean completed;
public TaskModel(String title) { this.title = title; this.completed = false; }
public String getTitle() { return title; }
public boolean isCompleted() { return completed; }
public void setCompleted(boolean completed) { this.completed = completed; }
}
// --- View ---
class TaskView {
public void displayTask(TaskModel task) {
String status = task.isCompleted() ? "[✓]" : "[ ]";
System.out.println(status + " " + task.getTitle());
}
public void showError(String message) {
System.out.println("ERROR: " + message);
}
}
// --- Controller ---
class TaskController {
private final TaskModel model;
private final TaskView view;
public TaskController(TaskModel model, TaskView view) {
this.model = model;
this.view = view;
}
public void markComplete() {
model.setCompleted(true);
view.displayTask(model);
}
public void render() {
view.displayTask(model);
}
}
public class Main {
public static void main(String[] args) {
TaskModel model = new TaskModel("Buy groceries");
TaskView view = new TaskView();
TaskController controller = new TaskController(model, view);
controller.render();
controller.markComplete();
}
}