MVC and Observer Pattern

Since I’m working on a rather small project, I decided to implement a simple version of the Model-View-Controller pattern. Here’s the basic idea:

trainer
|
\_ model
:  |_ app.py
:  |_ data.py
|
\_ view
:  |_ res
:  |_ view.py
|
|_ main.py

In the package model there are two modules: data, which knows relevant data (e.g. letter codes), and app, which contains logic. The class app.App should be used for requests from other modules.
Code related to the look of individual views can be found in view.view. Image resources are saved in the subfolder view.res.

The program is started by executing main.py, which contains the Controller. It loads app and view, instantiates classes and connects Observers with Observables.

The Observer Pattern

In general, this architecture is much more efficient when combined with the Observer Pattern. I’m so glad I learnt that one!

For example, statistics need to be displayed correctly at all times. Normally, I would try to pass data to the view object whenever it should be displayed. This works, but it is very hard to read. Also, a lot of extra code is needed.
Instead, the view should observe the statistics object. Whenever data is updated, the view is notified automatically. That’s it! No additional code is required.
But how does the statistics object get new data? You might have guessed it: It observes quiz terminations. Those need to be observed by result views anyway, so there’s no need to rewrite anything at all.

As a side note, python supports passing methods around. There’s no need for an Observer class; Observables simply call stored callback functions instead. In my opinion, this might be the most pythonic solution.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s