Re: Observer pattern limitations



On 10 Jul 2006 02:31:26 -0700, David Barrett-Lennard wrote:

PROBLEM 1: Infinite recursion in notifications.

Use asynchronous notification services. Design notifications as independent
types (objects), you might wish to split "data change" and "visual
appearance change" events. Notifications need not to be hard callbacks. It
is the simplest possible mechanism, but it is not the only one.

[ The problem is known in middleware systems. You cannot mix notification
upon each change by each subscriber with an ability to make changes upon a
notification. The result is either deadlock or loss of a notification. ]

PROBLEM 2: Dirty reads.

Use protected objects. Behavior should be encapsulated in a protected
action on it. Note that "read" is not yet a behavior, it is a low-level
operation. Low-level tend to be dirty.

PROBLEM 3: Observer attaches or detaches during a notification

It is racing condition, when allowed to happen asynchronously.

The problem is that while a subject is notifying one of the observers,
an observer decides to attach or detach to/from the subject. This may
cause a crash depending on the data structure used by the subject to
store the observers.

This is not a problem, it is a bug. List and its iterators are objects. So
it is legal to modify the list while iterating it.

One hack I've seen to solve this problem is to use a "one shot
observer". Another is to make a copy of the list of observers before
issuing the notifications.

There are many solutions. For example, observers can be limited to wait for
exactly one event at a time.

PROBLEM 4: Memory management problems

There seems to only be one general solution (that I can think of). A
subject needs to hold strong references on its observers.

Well, usually it is a weak reference observer->subject. Clearly each weak
reference is a strong one in the backward direction. But implementations
don't care about it, because finalization of an observer finalizes the
reference with it. So there is nothing to care about.

PROBLEM 5: Nested contract attachments

Huh, a container of observers is itself an observer. Or dually, a set of
events is an event.

SO WHAT'S THE SOLUTION? : I have only found one general solution
to these problems. Basically it is to throw away the observer pattern
(unless you're doing a trivial problem that (provably) doesn't
suffer from these issues), and instead use a more general
graph-theoretic approach, such as the theory of one way or multi way
constraints, or the spread *** algorithm etc.

.... and it solves all problems? ...

I highly recommend you to publish *the* solution in a renown scientific
magazine, rather than wasting your time in an Internet newsgroup.

(My apologies to comp.object (:-))

--
Regards,
Dmitry A. Kazakov
http://www.dmitry-kazakov.de
.


Quantcast