CS102 – Bilkent University 06/25/12 MVC and GUIs Use of the model, view, controller design pattern in graphical user interfaces CS102 – Bilkent University
MVC (Model, View, Controller) 06/25/12 MVC (Model, View, Controller) Used to build GUI applications Separation of concerns Easy to maintain and update Model: The model represents data and the rules that govern access to and updates of this data. View: The view renders the contents of a model. If the model data changes, the view must update its presentation. Controller: The controller translates the user's interactions with the view into actions that the model will perform. Copyright © 2012 Pearson Education, Inc.
A common MVC implementation 06/25/12 A common MVC implementation
Interaction Between MVC Comps. 06/25/12 Interaction Between MVC Comps. The view: Renders the model when needed (when relevant changes happen). Registers as a listener on the model. Changes on the model will invoke a listener method in the view class. Notifies the controller when the user interacts with the view. The controller: Registers as a listener on the view. User actions performed on the view will invoke a listener method in the controller class. Updates the model based on user input (which it learns through listener calls from the view) by applying its own control policies. Copyright © 2012 Pearson Education, Inc.
Interaction Between MVC Comps. 06/25/12 Interaction Between MVC Comps. The model: Notifies the view when the model changes. Provides inspection methods to the view. Provides manipulation methods to the controller. Copyright © 2012 Pearson Education, Inc.
A Java SE Application Using MVC 06/25/12 A Java SE Application Using MVC
A Typical Interaction User changes the text: 06/25/12 A Typical Interaction User changes the text: The view notifies the controller of the change The controller updates the model The model notifies the view of the change The view redraws to reflect the change Advantages: There could be multiple views of the same model Control policies can be applied without cluttering the main jobs of rendering state (view) and managing it (model) Copyright © 2012 Pearson Education, Inc.
More than one view Multiple Views Using the Same Model 06/25/12 Copyright © 2012 Pearson Education, Inc.
06/25/12 Variations on MVC In this variation, we have the controller arbitrating between the model → view notifications. Apple Cocoa framework uses this variation of MVC. Copyright © 2012 Pearson Education, Inc.
06/25/12 Self-exercise Read the code example at: http://www.oracle.com/technetwork/articles/javase/index- 142890.html#4 Copyright © 2012 Pearson Education, Inc.