Model View Controller (MVC)
One of the key design patterns in mainstream use is that of the Model View Controller (MVC). This pattern allows you to separate the following in your code:
- Model. The underlying data model.
- View. The user view of the data.
- Controller. The manner in which modifications are allowed to the data.
The example code above uses the same approach. Listing 5 illustrates the Model interface.
Listing 5 The Model interface.
public interface Model { public String getMessage(); }
The model in this simple example contains just a single String object. Next up, we have the View interface in Listing 6.
Listing 6 The View interface.
public interface View { public void render(); public void setModel(Model m); public Model getModel(); }
The View interface allows you to set up the model, retrieve the model, and render the view of the model.
Java doesn't allow you to instantiate an interface. You must implement or extend an interface; Listing 7 shows an example, where the View interface is implemented by the class StandardOutView.
Listing 7 Rendering the view.
public class StandardOutView implements View { private Model model = null; public void render() { if (model == null) { throw new RuntimeException( "You must set the property model of class named:" + StandardOutView.class.getName()); } System.out.println(model.getMessage()); } public void setModel(Model m) { this.model = m; } public Model getModel() { return this.model; } }
As Listing 7 shows, we have three methods. One method renders the view (prints the model message). The other two methods set and get the model.