Model-View-Controller

Definition: The model holds all the data, state, and application logic. The controller takes user input and changes the model appropriately. The view provides a visual presentation of the model.

This is actually a compound pattern of several patterns. The controller is a Strategy pattern that configures the view. The model is an Observer that observes the controller to see how it changes. Everything is decoupled.

Usage: This class is typically used to split gui widgets into 3 parts so that you can change one part without changing the others.

Example

class TextField {
	TextField() {
		this(new TextFieldController(this), new TextFieldModel())
	}

	TextField(TextFieldController controller, TextFieldModel model) {
		setController(controller)
		setModel(model)
	}

	draw(Graphics g) {
		output getModel().getText()
	}

	TextFieldController getController() {return controller}

	TextFieldModel getModel() {return model}

	setController(TextFieldController controller) {this.controller = controller}

	setModel(TextFieldModel model) {this.model = model}

	TextFieldController controller;
	TextFieldModel model;
}

class TextFieldController {
	TextFieldController(TextField field) {
		this.field = field
	}

	respondToKeyEvent(KeyEvent event) {
		TextFieldModel model = field.getModel();
		String text = model.getText();
		update text to match the event
		model.setText(text)
	}

	TextField field
}

class TextFieldModel {
	TextFieldModel() {
		setText("")
	}

	getText() {return text}
	setText(String text) {this.text = text}

	String text
}

The point of all this is so that the TextFieldController and TextFieldModel classes can be subclassed without having to subclass the TextField itself.

Index

Copyright (C) 2008 Steven Fletcher. All rights reserved.