< Day Day Up > |
The Model-View-Controller (MVC) design pattern separates user interface code into three distinct classes:
For example, in a toggle button, the model would store the state of the button (on or off), the view would draw the button on screen, and the controller would set the state of the button in the model (to on or off) when the button is clicked. But an interface need not be visual. In some cases, the view might play a sound or, as a non-ActionScript example, the view might make a video game controller vibrate. MVC originated in the Smalltalk language and has been used widely for years in many different incarnations. Though the basic principles of the pattern are easy to understand, its details are complex enough to foster an enormous amount of debate and contradictory implementations . In this chapter, we'll study a relatively traditional implementation of the pattern, bearing in mind that there is no single "right" way to implement MVC. The basic principle of MVC is the separation of responsibilities. In an MVC application, the model class concerns itself only with the application's state and logic. It has no interest in how that state is represented to the user or how user input is received. By contrast, the view class concerns itself only with creating the user interface in response to generic updates it receives from the model. It doesn't care about application logic nor about the processing of input; it just makes sure that the interface reflects the current state of the model. Finally, the controller class is occupied solely with translating user input (provided by the view) into updates that it passes to the model. It doesn't care how the input is received or what the model does with those updates. Separating the code that governs a user interface into the model, view, and controller classes yields the following benefits:
Despite those benefits, not all user interfaces are best implemented with MVC. For example, in Chapter 12 we built a simple currency converter application using a single class, CurrencyConverter . The conceptual responsibilities of the model, view, and controller were still manifest in that application, but they were encompassed by a single class. The currency converter application was so simple that the cost of implementing formal MVC outweighed the benefits.
The MVC pattern can be applied to a single user interface element (like a button), to a group of user interface elements (like a control panel), or to an entire application. This chapter uses MVC to create a clock that combines three user interface elements: a digital display, an analog display, and a toolbar for starting, stopping, and resetting the clock. |
< Day Day Up > |