Download COMP 542 Object Oriented Programming

Transcript
COMP 542/4 E
Winter 2000
109
This description is somewhat idealized. In practice, the view usually communicates directly
with the model because this is easier and more efficient than negotiating via the controller.
MVC is often implemented as a framework. This means that the model, view, and controller
are abstract base classes that specify channels of communication. A program is implemented
by deriving concrete classes from the base classes.
The following program is an extremely simple example of the MVC framework. Here are
abstract base classes for the model and the view.
(Complete code on web page.)
class Model
{
public:
virtual int finished () { return false; }
virtual void update () = 0;
virtual double report () = 0;
};
class View
{
public:
virtual int finished () { return false; }
virtual void update (double observable) = 0;
};
The class Controller is concrete here although in a practical application it should be abstract.
class Controller
{
public:
Controller (Model *model, View *view);
void run ();
private:
Model *model;
View *view;
};
The constructor is given a model and a view. Its run() method simply updates the model
and the view until one of them indicates that it is finished or — as a safety precaution! — a
fixed number of cycles have been executed.
Controller::Controller (Model *model, View *view)
{
Controller::model = model;
Controller::view = view;
}
void Controller::run ()