The Observer Pattern

Gustave Doré's illustration to the European fa...
Image via Wikipedia

This pattern is also known as publish/subscribe. It’s mainly used for keeping objects updated. The object sending out updates is called the “Subject” and the objects receiving updates are called “Observers.”

As a one-to-many example, think of Little Red Riding Hood (LRRH…she recently converted to Scientology. It was on TMZ). She’s setting up Grandma’s RSS feed for the very first time.
Grandma only has 1 feed, from her favorite televangelist, Mozelle Patterson. Grandma only has one feed because after LRRH set it up for her, she’s probably not going to go looking for more.

Mozelle Patterson is a televangelist here in the ATL who has a show on a local channel every Saturday that can, at times, be more amusing than SNL. Let’s say Mozelle Patterson has an RSS feed. Her feed is the subject. All the grandmas who have had someone set up their RSS feed, get the Mozelle Patterson feed. All of the grandmas, including LRRH’s, are the observers.

**subject**

Mozelle

|

|

v

** observer**
-Little Red Riding Hood’s Grandma

**observer**

-Sleeping Beauty’s Grandma

**observer**
-Anansi’s Grandma

Notice that, previously, I said that this is the 1 to many example. Why? Because the next time LRRH visits, she notices that Grandma hasn’t added anymore feeds, but she knows that Mozelle has a special feed specifically for the Gospel music featured on the show, and she adds that to Grandma’s reader. Now, Grandma has 2 different types of feeds from the same place. That’s many to many.

Here’s a class diagram of the 1-to-many example. Note: this is my example, and it’s not guaranteed to be perfect, so don’t take it as “gospel.”

The Observer Pattern
The Observer Pattern

Push/Pull
There are two types of Subject/Observer relationshiop. In the “Push” relationship, the Subject will send the observer everything it needs on notify. For example, If Mozelle’s rss feed contained all of the highlight from the show with pictures, etc., this would be a push. If the feed only contained the title of the show, and Grandma had to click through to view the show highlights, then it would be a pull relationship.

Loose Coupling
This pattern is a great example of loose coupling, because the subject doesn’t know that much about its observers. The observers operate freely and independatly of their updates from the Subject.

Reblog this post [with Zemanta]