Apr 22 2006

The Observer Pattern

Category: Design PatternsBil@l @ 10:25

The pattern I am going to talk about today is the Observer Pattern. Another new and cool pattern to discuss.

Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Not clear? Its ok, we'll restate again.

The idea is simple, take the example of the publisher and subscibers!

A newspaper paper publisher publihes newspaper every morning right? nothing new :)

Suppose I am company X, and want to have the newspaper arrive to my officies every morning.

So I(observer) go to the publisher (subject) and tell him/her please I want to subscribe to your newspaper to get my newspaper (update) every morning.

What happens is that, once a new newspaper is published every morning, the publisher will update my office with that new newspaper.

So the main players are the Subject and Observer. The observer registers with the Subject, then the subject's responsiblity to update the state of each observer registered. Observers can register and unregister from a subject.

Usually we use two interfaces, one for the subject and one for the observers. This way any object wants to register with the subject has only to implement that interface.

Hope this helps you,

Regards

Tags:

Comments are closed