[Tutor] Correct use of model-view-controller design pattern

Alan Gauld alan.gauld at yahoo.co.uk
Tue May 31 04:35:54 EDT 2016


On 31/05/16 02:25, boB Stepp wrote:

> This "views register with models" and "registered views" terminology
> is unfamiliar to me.  Googling suggests registered views is referring
> to a dynamically generated presentation, perhaps in the sense of a db

No, this is different.
Try googling publish-subscribe instead.

The pattern is that something has data to publish (the model)
and other things want to know about when the data changes
(the associated view(s)). So when a view is created it knows which
model(s) it wants updates from and registers with them. (The model
has a register() method that adds the new view to a list of subscribers.)

When something changes on the model it calls its publish() method
which simply traverses the subscriber list and sends an update() message
to each (usually with itself as the argument).

The view can then interrogate the model to see if any of the
data changes affect its display and, if so, make the
corresponding updates on the UI.

When a view is deleted it unregisters from the model.

In summary:

- A view constructor must have a model parameter
  and register with the model.
- A view must implement an update() method
- A view destructor must unregister itself from the model

- A Model must have a register() method
- A Model must have an unregister() method
- A model must have a publish() method

This mechanism is most commonly used where the view/controller
are combined into a single implementation entity.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list