observer pattern question #1 (reference to subject)

Ville M. Vainio vivainio at gmail.com
Thu May 8 16:53:37 EDT 2008


Alan Isaac <aisaac at american.edu> writes:

> the following: "OK, here's the pattern, now your listener
> wants to know the event source, do not ask something new the
> subject to respond to that need.  That is unnecessary
> coupling.  Instead, just rewrite your listener to maintain
> a reference to the subject."
>
> Do I have that right?

Not really. It has to be determined case-by-case. Note that I'm not
arguing *for* not passing "subject" on notification, just trying to
elaborate on situations that might want to choose that route.

> It seems to me that this response begs the question.
> That is, an appropriate reply seems to be: here is a related
> pattern, call it observer2.  In the observer2 pattern, the
> subject has a getState method and always passes itself when
> it notifies the observer. Now: in what sense does this
> require closer coupling?

It creates stronger connection between the subject and observer,
thereby reducing the amount different of places that can call the
observer (I don't mean different stock, but altogether different
places - say, a central stock controller that can broadcast the change
in several stocks at the time by stock id, once per second).

This is not really a feature of the observer pattern, both approaches
are somewhat valid observer patterns, depending on problem domain. If
you think it makes sense in the first place to have ONE reference to
the subject in observer, it's probably a workable approach - but in
case of stocks, you are probably monitoring several stock objects, so
the stock should probably pass itself to the observer (so that you
don't need to check all stocks every time something changes!).

Of course this stock thing is a bad example for this case, because you
have several stocks per investor. It's analogous to a typical UI
scenario where you have several widgets forwarding events to one big 
observer - and they *do* provide the event source and event type.

> Or to put it a different way, your suggestion that the
> investors should have to *pull* this information from the
> stocks seems out of step with the observer pattern, where
> the stocks should be pushing this information to the
> investor.

It's not necessarily the observer that has the interesting
information. It's quite typical to have general "catch-all"
notifications than report observers that "something has
chanced somewhere, so you should refresh your data". 

All in all, though, the right solution should be obvious from the
problem at hand.



More information about the Python-list mailing list