Observer

AKA: dependents, Publish-Subscribe

When you have some objects reacting to events over time, we’ll call these the Celebrities, other objects may want to react to their activity. When the Celebrities reach a specific state or take a particular action, these Fan objects want to know about it.

Polling is either expensive if done too often or misses events if not done often enough. One solution you might have is an event log containing everything every Celebrity does. Each Fan can filter the log for the events they’re interested in, but filtering takes time.

It would be better if the Celebrity events a Fan was interested in directly triggered an event on the Fan.

Observer

The implementation of the Observer class uses a protected Notify method so the Celebrities can post to their Fans. The simplest implementations send events to all fans on every change. This has two main issues.

The first is the broadness. Take care when creating Publications for changes. Changes can cascade, and small changes may go unnoticed without paying close attention. The default Update implementation does not include information about what changed. You could add it, but it would require introducing parameters to the update and notify methods specifying this, and some languages don’t have the flexibility to add the information efficiently.

The second issue has to do with entity lifetimes. I have an issue with object creation events. If we create a Celebrity, a Fan cannot learn of this by the Observer pattern as they cannot subscribe to an object that does not exist. Instead, there is a need for a broker of some sort to allow subscription to an as-yet non-existent Celebrity by some form of identifier.

Event logs can get around these concerns by keeping their events in a tree. Subscription can be written as a filtering expression of the tree, such as you might specify a folder in a file system. A publisher can then publish their updates to a subset of the tree, limiting detailed messages to only the actively interested Fans.

All this leads to a general pattern of messaging systems, but the GoF book has nothing to say about this. Instead, I would recommend reading up on the many messaging-related patterns in Enterprise Integration Patterns[EIP04].

“Subscribe now and never miss any of my content.”